How to kill all child processes (spawned using child_process.spawn) when node.js process exit?
If you deliberately kill the intermediate process, then the child won't be killed when the parent dies. If the child exits before the parent, then the intermediate process will try to kill the original child pid, which could now refer to a different process.
For killing a child process after a given timeout, we can use the timeout command. It runs the command passed to it and kills it with the SIGTERM signal after the given timeout. In case we want to send a different signal like SIGINT to the process, we can use the –signal flag.
You can kill all child processes by first getting a list of all active child processes via the multiprocessing. active_children() function then calling either terminate() or kill() on each process instance.
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).
I think the only way is to keep a reference to the ChildProcess
object returned by spawn
, and kill it when you exit the master process.
A small example:
var spawn = require('child_process').spawn; var children = []; process.on('exit', function() { console.log('killing', children.length, 'child processes'); children.forEach(function(child) { child.kill(); }); }); children.push(spawn('/bin/sleep', [ '10' ])); children.push(spawn('/bin/sleep', [ '10' ])); children.push(spawn('/bin/sleep', [ '10' ])); setTimeout(function() { process.exit(0) }, 3000);
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