-
Notifications
You must be signed in to change notification settings - Fork 414
/
process-utils.ts
41 lines (35 loc) · 982 Bytes
/
process-utils.ts
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
'use strict';
import { ChildProcess } from 'child_process';
function onExitOnce(child: ChildProcess): Promise<void> {
return new Promise(resolve => {
child.once('exit', () => resolve());
});
}
function hasProcessExited(child: ChildProcess): boolean {
return !!(child.exitCode !== null || child.signalCode);
}
/**
* Sends a kill signal to a child resolving when the child has exited,
* resorting to SIGKILL if the given timeout is reached
*/
export async function killAsync(
child: ChildProcess,
signal: 'SIGTERM' | 'SIGKILL' = 'SIGKILL',
timeoutMs: number = undefined,
): Promise<void> {
if (hasProcessExited(child)) {
return;
}
const onExit = onExitOnce(child);
child.kill(signal);
if (timeoutMs === 0 || isFinite(timeoutMs)) {
const timeoutHandle = setTimeout(() => {
if (!hasProcessExited(child)) {
child.kill('SIGKILL');
}
}, timeoutMs);
await onExit;
clearTimeout(timeoutHandle);
}
await onExit;
}