kill all child_process when node process is killed

Problem

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){});
Problem courtesy of: Phani

Solution

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();
});
Solution courtesy of: fakewaffle

Discussion

what about to use the exit event, so when the main process is about to exit you can kill the child_process

process.on('exit', function() {
  console.log('process is about to exit, kill ffmpeg');
  child_process.kill();
});
Discussion courtesy of: alfonsodev

This recipe can be found in it's original form on Stack Over Flow.