kill all child_process when node process is killed

柔情痞子 提交于 2019-12-03 14:56:46

问题


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

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.

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

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

回答1:


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();
});



回答2:


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

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 fakewaffle solution 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.



来源:https://stackoverflow.com/questions/18275809/kill-all-child-process-when-node-process-is-killed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!