Created
July 2, 2020 10:44
-
-
Save michi88/48e1b3b8530163b45ce1db75aa35451e to your computer and use it in GitHub Desktop.
SIGINT spawn testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
}); |
Author
michi88
commented
Jul 2, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment