justinhelmer
1/15/2016 - 10:35 PM

Properly clean up a node process and its child processes when it receives various signals

Properly clean up a node process and its child processes when it receives various signals


process.stdin.resume();

process.on('exit', exitHandler);
process.on('SIGINT', _.partial(exitHandler, {exit: 2}));
process.on('uncaughtException', _.partial(exitHandler, {exit: 99}));

var children = [];
function exitHandler(options, err) {
  grunt.log.writeln('');

  if (err && err.stack) {
    grunt.fail.fatal(err, 1);
  }

  if (children.length) {
    grunt.log.writeln('Killing ' + (children.length + '').blue + ' background process(es)...');
    _.invoke(children, 'kill');
    children = []; // exitHandler may be hit multiple times for certain signals
  }

  if (_.get(options, 'exit')) {
    process.exit(options.exit);
  }
}