Skip to content

Instantly share code, notes, and snippets.

@hinzundcode
Created February 4, 2018 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hinzundcode/a426abd1a7fc0a55afc44a1b53c2f082 to your computer and use it in GitHub Desktop.
Save hinzundcode/a426abd1a7fc0a55afc44a1b53c2f082 to your computer and use it in GitHub Desktop.
"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