From adc7c5dfea2b6d433ab767d166398400f7c4a5c3 Mon Sep 17 00:00:00 2001 From: Marcel Kottmann Date: Fri, 7 Jun 2019 16:40:32 +0200 Subject: [PATCH] fix: wait for all child processes to terminate (fixes issue #1476) --- lib/monitor/run.js | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/lib/monitor/run.js b/lib/monitor/run.js index 7084c6bf..82a32c87 100644 --- a/lib/monitor/run.js +++ b/lib/monitor/run.js @@ -16,6 +16,27 @@ var psTree = require('pstree.remy'); var path = require('path'); var signals = require('./signals'); +function waitForOldKids(oldKids, callback) { + if (oldKids) { + // check if all previous kids have been terminated + exec('kill -0 ' + oldKids.join(' '), (error) => { + const returnCode = error ? error.code : 0; + if (returnCode < 126) { // ignore command not found error + const stillRunningKids = oldKids.length - returnCode; + if (stillRunningKids > 0) { + utils.log.status('still waiting for ' + stillRunningKids + + ' child process(es) to finish...'); + setTimeout(waitForOldKids.bind(this, oldKids, callback), 100); + return; + } + } + callback(); + }); + } else { + callback(); + } +} + function run(options) { var cmd = config.command.raw; @@ -343,15 +364,21 @@ function kill(child, signal, callback) { const sig = signal.replace('SIG', ''); psTree(child.pid, function (err, kids) { if (psTree.hasPS) { - spawn('kill', ['-s', sig, child.pid].concat(kids)) - .on('close', callback); + spawn('kill', ['-s', sig].concat(kids)) + .on('close', waitForOldKids.bind(this, kids, function () { + spawn('kill', ['-s', sig, child.pid]) + .on('close', callback); + })); } else { // make sure we kill from smallest to largest - const pids = kids.concat(child.pid).sort(); + const pids = kids.slice().sort(); pids.forEach(pid => { exec('kill -' + signals[signal] + ' ' + pid, () => { }); }); - callback(); + waitForOldKids(kids, function () { + exec('kill -' + signals[signal] + ' ' + child.pid, () => { }); + callback(); + }) } });