-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
68 lines (55 loc) · 2.02 KB
/
index.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { ChildProcess, execSync, spawn } from 'child_process';
interface dictionaryOfStringChildProcessArray {
[key: string]: ChildProcess[];
}
const children: dictionaryOfStringChildProcessArray = {};
export const killSubProcesses = function (owner: string) {
console.log(`killing ${owner} child processes (${children[owner].length})`);
children[owner].forEach((c) => {
try {
if (c.pid) {
if (process.platform === 'win32') {
execSync(`taskkill /pid ${c.pid} /T /F`);
} else {
process.kill(-c.pid);
}
}
} catch {}
});
};
process.on('exit', () => Object.keys(children).forEach((owner) => killSubProcesses(owner)));
function gracefulExitHandler() {
console.log('Handling termination signal to gracefully exit process')
process.exit()
}
process.on('SIGINT', gracefulExitHandler)
process.on('SIGTERM', gracefulExitHandler)
process.on('SIGQUIT', gracefulExitHandler)
const spawnSubProcess = (owner: string, command: string, showOutput: boolean) => {
const [binary, ...rest] = command.split(' ');
const childProcess = spawn(binary, rest, {
stdio: showOutput ? 'inherit' : 'ignore',
detached: true,
});
children[owner] = children[owner] || [];
children[owner].push(childProcess);
return childProcess;
};
const spawnSubProcessOnWindows = (owner: string, command: string, showOutput: boolean) => {
const childProcess = spawn(process.env.comspec || 'cmd.exe', ['/c', ...command.split(' ')], {
stdio: showOutput ? 'inherit' : 'ignore',
});
children[owner] = children[owner] || [];
children[owner].push(childProcess);
return childProcess;
};
export const subProcess = (owner: string, command: string, showOutput: boolean) => {
if (process.platform === 'win32') {
return spawnSubProcessOnWindows(owner, command, showOutput);
} else {
return spawnSubProcess(owner, command, showOutput);
}
};
export const subProcessSync = (command: string, showOutput: boolean) => {
return execSync(command, { stdio: showOutput ? 'inherit' : 'ignore' });
};