Skip to content

Instantly share code, notes, and snippets.

@michi88
Created July 2, 2020 10:44
Show Gist options
  • Save michi88/48e1b3b8530163b45ce1db75aa35451e to your computer and use it in GitHub Desktop.
Save michi88/48e1b3b8530163b45ce1db75aa35451e to your computer and use it in GitHub Desktop.
SIGINT spawn testing
const http = require("http");
const spawn = require("child_process").spawn;
const IS_CHILD = process.argv[2] === "--child";
const DETACHED = process.argv[2] === "--detached";
const port = IS_CHILD ? 3001 : 3000;
const requestHandler = (request, response) => {
console.log(request.url);
response.end("Hello Node.js Server!");
};
let child = null;
if (!IS_CHILD) {
child = spawn("node", ["index.js", "--child"], {
stdio: "inherit",
detached: DETACHED
});
}
const log = (message, ...args) => {
console.log((IS_CHILD ? "Child: " : "Parent: ") + message, ...args);
};
const server = http.createServer(requestHandler);
server.listen(port, err => {
if (err) {
return log("something bad happened", err);
}
log(`server is listening on ${port}`);
});
const close = () => {
log("Closing");
if (child) {
log("Killing child");
child.kill("SIGTERM");
}
server.close(() => {
log("Http server closed.");
});
process.exit();
};
["SIGTERM", "SIGHUP", "SIGQUIT"].forEach(function(signal) {
process.on(signal, function() {
log("received signal", signal);
log("Closing http server.");
close();
});
});
let sigints = 0;
process.on("SIGINT", () => {
if (IS_CHILD && !DETACHED) {
log("received SIGINT, ignoring...");
return;
}
sigints = sigints + 1;
if (sigints < 2) {
log("received first SIGINT, ignoring...");
} else {
log("received another SIGINT, closing");
close();
}
});
@michi88
Copy link
Author

michi88 commented Jul 2, 2020

$ node index.js
Parent: server is listening on 3000
Child: server is listening on 3001
^CParent: received first SIGINT, ignoring...
Child: received SIGINT, ignoring...
^CChild: received SIGINT, ignoring...
Parent: received another SIGINT, closing
Parent: Closing
Parent: Killing child
Child: received signal SIGTERM
Child: Closing http server.
Child: Closing
$ node index.js --detached
Parent: server is listening on 3000
Child: server is listening on 3001
^CParent: received first SIGINT, ignoring...
^CParent: received another SIGINT, closing
Parent: Closing
Parent: Killing child
Child: received signal SIGTERM
Child: Closing http server.
Child: Closing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment