process.js
1.08 KB
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
import { exec } from 'teen_process';
/*
* Exit Status for pgrep and pkill (`man pkill`)
* 0. One or more processes matched the criteria.
* 1. No processes matched.
* 2. Syntax error in the command line.
* 3. Fatal error: out of memory etc.
*/
async function getProcessIds (appName) {
let pids;
try {
let {stdout} = await exec('pgrep', ['-x', appName]);
pids = stdout.trim().split('\n').map((pid) => parseInt(pid, 10));
} catch (err) {
if (parseInt(err.code, 10) !== 1) {
throw new Error(`Error getting process ids for app '${appName}': ${err.message}`);
}
pids = [];
}
return pids;
}
async function killProcess (appName, force = false) {
let pids = await getProcessIds(appName);
if (pids.length === 0) {
// the process is not running
return;
}
try {
let args = force ? ['-9'] : [];
args.push('-x', appName);
await exec('pkill', args);
} catch (err) {
if (parseInt(err.code, 10) !== 1) {
throw new Error(`Error killing app '${appName}' with pkill: ${err.message}`);
}
}
}
export { getProcessIds, killProcess };