Skip to content

Commit 90fc149

Browse files
fix: wait for all subprocesses to terminate (fixes issue #1476)
1 parent 7d6c1a8 commit 90fc149

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

Diff for: lib/monitor/run.js

+34-5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,28 @@ var psTree = require('pstree.remy');
1616
var path = require('path');
1717
var signals = require('./signals');
1818

19+
function waitForSubprocesses(subprocesses, callback) {
20+
if (Array.isArray(subprocesses) && subprocesses.length > 0) {
21+
// check if all old subprocesses have been terminated
22+
exec('kill -0 ' + subprocesses.join(' '), (error) => {
23+
const returnCode = error ? error.code : 0;
24+
if (returnCode < 126) { // ignore command not found error
25+
const stillRunning = subprocesses.length - returnCode;
26+
if (stillRunning > 0) {
27+
utils.log.status('still waiting for ' + stillRunning +
28+
' subprocess(es) to finish...');
29+
setTimeout(waitForSubprocesses.bind(this, subprocesses, callback),
30+
100);
31+
return;
32+
}
33+
}
34+
callback();
35+
});
36+
} else {
37+
callback();
38+
}
39+
}
40+
1941
function run(options) {
2042
var cmd = config.command.raw;
2143

@@ -341,17 +363,24 @@ function kill(child, signal, callback) {
341363
// configured signal (default: SIGUSR2) signal, which fixes #335
342364
// note that psTree also works if `ps` is missing by looking in /proc
343365
const sig = signal.replace('SIG', '');
344-
psTree(child.pid, function (err, kids) {
366+
psTree(child.pid, function (err, subprocesses) {
345367
if (psTree.hasPS) {
346-
spawn('kill', ['-s', sig, child.pid].concat(kids))
347-
.on('close', callback);
368+
spawn('kill', ['-s', sig].concat(subprocesses))
369+
.on('close', waitForSubprocesses.bind(this, subprocesses,
370+
function () {
371+
spawn('kill', ['-s', sig, child.pid])
372+
.on('close', callback);
373+
}));
348374
} else {
349375
// make sure we kill from smallest to largest
350-
const pids = kids.concat(child.pid).sort();
376+
const pids = subprocesses.slice().sort();
351377
pids.forEach(pid => {
352378
exec('kill -' + signals[signal] + ' ' + pid, () => { });
353379
});
354-
callback();
380+
waitForSubprocesses(subprocesses, function () {
381+
exec('kill -' + signals[signal] + ' ' + child.pid, () => { });
382+
callback();
383+
})
355384
}
356385
});
357386

0 commit comments

Comments
 (0)