node.js 杀死节点进程时杀死所有子进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18275809/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:20:18  来源:igfitidea点击:

kill all child_process when node process is killed

node.jscluster-computingchild-process

提问by Phani

How do i make sure all child_process are killed when the parent process is killed. I have something like the below one.

当父进程被杀死时,我如何确保所有 child_process 都被杀死。我有类似下面的东西。

Even when the node process is kill i see that FFMPEG continues to run and the out.avi is generated. How can i stop FFMPEG from running after the node process exits.

即使节点进程被终止,我也会看到 FFMPEG 继续运行并生成了 out.avi。如何在节点进程退出后阻止 FFMPEG 运行。

var args = "ffmpeg -i in.avi out.avi"
child_process.exec(args , function(err, stdout,stderr){});

child_process.exec(args , function(err, stdout,stderr){});

回答by fakewaffle

You need to listen for the process exit event and kill the child processes then. This should work for you:

您需要监听进程退出事件,然后杀死子进程。这应该适合你:

var args = "ffmpeg -i in.avi out.avi"
var a = child_process.exec(args , function(err, stdout,stderr){});

var b = child_process.exec(args , function(err, stdout,stderr){});

process.on('exit', function () {
    a.kill();
    b.kill();
});

回答by alfonsodev

You could listen for exit process event, so when the main process is about to exit you have time to call kill method on the ffmpeg child process

您可以监听退出进程事件,因此当主进程即将退出时,您有时间在 ffmpeg 子进程上调用 kill 方法

var args = "ffmpeg -i in.avi out.avi"
var ffmpegChildProccess = child_process.exec(args , function(err, stdout,stderr){});

process.on('exit', function() {
  console.log('process is about to exit, kill ffmpeg');
  ffmpegChildProccess.kill();
});

Edit: as comments are mentioning and fakewafflesolution got right, kill is not to be called in child_process but in the reference to the child process that you get when performing exec.
Also I remove the "what a about ..." because was unnecessary and unintentionally I realise it was sounding harsh when reading it out loud.

编辑:正如评论中提到的和fakewaffle解决方案是正确的,kill 不是在 child_process 中调用,而是在执行 exec 时获得的子进程的引用中调用。
我还删除了“what a about ...”,因为这是不必要的,而且我无意中意识到大声朗读时听起来很刺耳。