kill all child_process when node process is killed
Asked Answered
D

2

26

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){});
Dillingham answered 16/8, 2013 at 14:35 Comment(0)
H
31

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();
});
Haldane answered 16/8, 2013 at 15:6 Comment(3)
What happens if process a finishes before the main process triggers the exit event and the a.kill() gets called. Won't this have the possibility that it could kill another process that was reassigned to the same PID that a used to be? How do you prevent this?Coastwise
Maybe a stupid question, but do I always need to invoke kill on my child_process? I have a bug in my code related to memory, and thought maybe something crazy like that is generating it...Glade
@Coastwise I think the solution is to add an event handler that triggers when the child exits, and do something (such as setting the process variable to null or something) so the parent process will know not to kill it.Gamages
E
-3

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.

Eurhythmic answered 16/8, 2013 at 15:3 Comment(3)
child_process module does not have kill.Finney
That's the child process object, not child_process module.Finney
You are missing that you have to store the reference to the child process and then kill on that.Finney

© 2022 - 2024 — McMap. All rights reserved.