node.js 如何在退出时杀死所有子进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15833047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to kill all child processes on exit?
提问by Sirian
How to kill all child processes (spawned using child_process.spawn) when node.js process exit?
node.js进程退出时如何杀死所有子进程(使用child_process.spawn产生)?
回答by robertklep
I think the only way is to keep a reference to the ChildProcessobject returned by spawn, and kill it when you exit the master process.
我认为唯一的方法是保留对由ChildProcess返回的对象的引用spawn,并在退出主进程时将其杀死。
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);
回答by DuBistKomisch
To add to @robertklep's answer:
添加到@robertklep 的答案:
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.
如果像我一样,当 Node 被外部杀死而不是它自己选择时,你想这样做,你必须对信号做一些诡计。
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 exiton process!
关键是要听任何信号(S),你可以用被杀死,并呼吁process.exit()在默认情况下,否则节点将不会发出exit上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 exiton processnormally.
这样做后,就可以只听exit对process正常。
The only issue is SIGKILLcan't be caught, but that's by design. You should be killing with SIGTERM(the default) anyway.
唯一的问题是SIGKILL无法捕获,但这是设计使然。无论如何,您应该kill使用SIGTERM(默认值)。
See this questionfor more.
请参阅此问题了解更多信息。

