I have this function and fork a child process to run a heavy work on background. The work
module sends message after it completes the work. How do I kill or close the forked process?
function doWork() {
var child = cp.fork(__dirname + '/work');
child.on('message', function(m) {
console.log('completed: ' + m);
// try to kill child process when work signals it's done
child.kill('SIGHUP');
});
child.send({
msg: 'do work',
name: self.myname
});
}
-edit-
I tried child.kill('SIGHUP')
and child.kill();
when work signals it's done. I seems didn't kill the process. If I do ps | grep node
, it still shows the work process is alive. What am I missing?
kill('SIGINT');
Killing a parent doesn't kill the child processes Every process has a parent. We can observe this with pstree or the ps utility. The ps command displays the PID (id of the process), and the PPID (parent ID of the process).
To finish a child process, the exit() system call is used in the child process. The wait() function is defined in the header sys/wait. h and the exit() function is defined in the header stdlib.
Either parent or child can signal the other, and in fact each signal can kill the other process.
I hope I'm not too late!
You can try to get pid of the forked child and pass it to child as reference and when job is done send pid along with the completion signal and you can kill the process based on pid.
function doWork() {
var child = cp.fork(__dirname + '/work');
child.on('message', function(m) {
//try to pass pid along with the signal from child to parent
console.log('completed: ' + m);
//killing child process when work signals it's done
process.kill(m.pid);
});
child.send({
msg: 'do work',
name: self.myname,
pid : child.pid // passing pid to child
});
}
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