How to kill all child processes on exit?
如何在node.js进程退出时终止所有子进程(使用child_process.spawn生成)?
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);
To add to @robertklep's answer:
If, like me, you want to do this when Node is being killed externally, rather than of its own choice, you have to do some trickery with signals.
The key is to listen for whatever signal(s) you could be killed with, and call process.exit()
, otherwise Node by default won't emit exit
on process
!
var cleanExit = function() { process.exit() };
process.on('SIGINT', cleanExit); // catch ctrl-c
process.on('SIGTERM', cleanExit); // catch kill
After doing this, you can just listen to exit
on process
normally.
The only issue is SIGKILL
can't be caught, but that's by design. You should be kill
ing with SIGTERM
(the default) anyway.
See this question for more.
链接地址: http://www.djcxy.com/p/52710.html上一篇: 不使用命令提示符(winform或javascript)执行node.js?
下一篇: 如何在退出时终止所有子进程?