Skip to content

Instantly share code, notes, and snippets.

@hinzundcode

hinzundcode/pipe.js

Created Feb 4, 2018
Embed
What would you like to do?
"use strict";
const ffi = require("ffi");
const ref = require("ref");
const ArrayType = require("ref-array");
const { createReadStream, createWriteStream, readSync, writeSync, closeSync } = require("fs");
let IntArray = ArrayType("int");
let StringArray = ArrayType("string");
let voidPtr = ref.refType(ref.types.void);
let stdlib = ffi.Library(null, {
"fork": ["int", []],
"execvp": ["int", ["string", StringArray]],
"dup2": ["int", ["int", "int"]],
"wait4": ["int", ["int", "int", "int", voidPtr]],
"pipe": ["int", [IntArray]],
//"close": ["int", ["int"]],
"_exit": ["int", ["int"]],
});
const WNOHANG = 1;
process.on("SIGCHLD", () => {
console.log("SIGCHLD!");
while (true) {
let pid = stdlib.wait4(-1, 0, WNOHANG, ref.NULL);
if (pid <= 0) break;
console.log(`reaped zombie ${pid}`);
console.timeEnd("fork");
}
});
let pipefd = new IntArray(2);
let result = stdlib.pipe(pipefd);
if (result === -1)
throw new Error("pipe "+result);
console.time("fork");
let pid = stdlib.fork();
if (pid === 0) {
console.log("hello from child");
process.title = "child";
closeSync(pipefd[1]);
let buf = Buffer.alloc(1024);
let bytesRead = readSync(pipefd[0], buf, 0, 1024);
console.log(bytesRead);
console.log(buf.toString("utf8", 0, bytesRead));
//let stream = createReadStream(null, { fd: pipefd[0], autoClose: false });
//stream.pipe(process.stdout);
closeSync(pipefd[0]);
stdlib._exit(0);
} else if (pid < 0) {
console.log("error forking");
} else {
console.log("child has pid", pid);
process.title = "parent";
closeSync(pipefd[0]);
writeSync(pipefd[1], "hello\n");
closeSync(pipefd[1]);
//let stream = createWriteStream(null, { fd: pipefd[1] });
//stream.end("hello!\n");
setInterval(() => {}, 10000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment