-
Notifications
You must be signed in to change notification settings - Fork 19
/
handlePsTreeCallback.js
66 lines (60 loc) · 1.43 KB
/
handlePsTreeCallback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module.exports = function handlePsTreeCallback(
err,
children,
pid,
signal,
options,
callback
) {
signal = signal || 'SIGKILL';
options = options || {};
callback = callback || function noop() {};
var pollInterval = options.pollInterval || 500;
var timeout = options.timeout;
if (err) {
return callback(err);
}
var pids = children.map(function (child) {
return parseInt(child.PID);
});
pids.forEach(function (pid) {
try {
process.kill(pid, signal);
} catch (error) {
// ignore
}
});
try {
process.kill(pid, signal);
} catch (error) {
// don't ignore if killing the top-level process fails
return callback(error);
}
pids.push(pid);
var start = Date.now();
function getUnterminatedProcesses() {
var result = [];
for (var i = 0; i < pids.length; i++) {
var pid = pids[i];
try {
process.kill(pid, 0);
// success means it's still alive
result.push(pid);
} catch (error) {
// error means it's dead
}
}
return result;
}
function poll() {
var unterminated = getUnterminatedProcesses();
if (!unterminated.length) {
return callback(null);
} else if (Date.now() + pollInterval - start > timeout) {
return callback(new Error('timed out waiting for pids ' + unterminated.join(', ') + ' to exit'));
} else {
setTimeout(poll, pollInterval);
}
}
setTimeout(poll, 0);
};