I have NodeJS code like the following:
[myFile.js]
var path = require("path");
var cp = require("child_process");
var child = cp.spawn( "python",["HelloWorld.py"], { stdio:'pipe', });
child.stdout.on('data', (data) => {
console.log(`CHILD stdout: ${data }`);
});
child.stderr.on('data', (data) => {
console.log(`CHILD stderr: ${data}`);
});
process.on("SIGINT",()=>{
// close gracefully
console.log("Received SIGINT");
})
child.on('exit',(code)=>{console.log(`child Process exited with code ${code}`)})
and python script like:
[HelloWorld.py]
print 'Hi there'
import time
time.sleep(5)
I want to manage the shutdown gracefully, but when I start this code at the command line via:
> node myFile.js
and press control-C, I get this printed to the console:
^CReceived SIGINT
CHILD stdout: Hi there
CHILD stderr: Traceback (most recent call last):
File "HelloWorld.py", line 3, in <module>
time.sleep(5)
KeyboardInterrupt
child Process exited with code 1
indicating that python (running in the child process) received the '^C' keyboard event. However, I'd prefer exit the child process a bit more gracefully, rather than crashing on a keyboard interrupt.
I tried a variety of combinations for the options.stdio, including [undefined,'pipe','pipe']
(which didn't work), and ['ignore','pipe','pipe']
(which caused the child process to crash), and I tried worker.stdin.end()
(which also caused the child process to crash).
Is there a way to not inherit the standard in from the parent NodeJS process?
RTFM: setting options.detached to true
is what prevents propagating the kill signals, which (surprise) is how attached child processes are killed when the parent is killed...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With