utils.js
1.16 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
45
46
47
48
49
50
51
52
53
54
55
56
const spawn = require('child_process').spawn;
module.exports = { tree, pidsForTree, getStat };
function getStat() {
return new Promise(resolve => {
const command = `ls /proc | grep -E '^[0-9]+$' | xargs -I{} cat /proc/{}/stat`;
const child = spawn('sh', ['-c', command], {
stdio: ['pipe', 'pipe', 'pipe'],
});
var res = '';
child.stdout.on('data', data => (res += data));
child.on('close', () => resolve(res));
});
}
function template(s) {
var stat = null;
// 'pid', 'comm', 'state', 'ppid', 'pgrp'
// %d (%s) %c %d %d
s.replace(
/(\d+) \((.*?)\)\s(.+?)\s(\d+)\s/g,
(all, PID, COMMAND, STAT, PPID) => {
stat = { PID, COMMAND, PPID, STAT };
}
);
return stat;
}
function tree(stats) {
const processes = stats
.split('\n')
.map(template)
.filter(Boolean);
return processes;
}
function pidsForTree(tree, pid) {
if (typeof pid === 'number') {
pid = pid.toString();
}
const parents = [pid];
const children = [];
tree.forEach(proc => {
if (parents.indexOf(proc.PPID) !== -1) {
parents.push(proc.PID);
children.push(proc);
}
});
return children;
}