Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill all child processes on exit?

Tags:

node.js

How to kill all child processes (spawned using child_process.spawn) when node.js process exit?

like image 453
Sirian Avatar asked Apr 05 '13 11:04

Sirian


People also ask

Does exit kill child processes?

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.

How do you kill a child's 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.

How do you kill all child processes in Python?

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.

Does killing parent process kill child process?

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).


1 Answers

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); 
like image 68
robertklep Avatar answered Sep 26 '22 02:09

robertklep