forked from indexzero/ps-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (54 loc) · 1.58 KB
/
index.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
66
67
'use strict';
var spawn = require('child_process').spawn,
es = require('event-stream');
// helper method to return whether an array or string contains a value
var contains = function (source, value) {
return !!~source.indexOf(value);
};
var childrenOfPid = function (pid, callback) {
var headers;
// callback is a required argument
if (typeof callback !== 'function') {
throw new Error('childrenOfPid(pid, callback) expects callback');
}
// stringify the PID in case it's a number
pid = '' + pid;
es.connect(
spawn('ps', ['-A', '-o', 'ppid,pid']).stdout,
es.split(),
es.map(function (line, mapCallback) {
// this could parse a lot of Unix command output
var columns = line.trim().split(/\s+/);
if (!headers) {
headers = columns;
} else {
var row = {};
var headersCopy = headers.slice();
while (headersCopy.length) {
row[headersCopy.shift()] = headersCopy.length ?
columns.shift() :
columns.join(' ');
}
return mapCallback(null, row);
}
return mapCallback();
}),
es.writeArray(function (err, processes) {
var parents = [ pid ],
children = [];
processes.forEach(function (err, process) {
if (contains(parents, process.PPID)) {
parents.push(process.PID);
children.push(process);
}
});
callback(null, children);
})
)
.on('error', callback);
};
if (!module.parent) {
childrenOfPid(process.argv[2] || 1, function (err, data) {
console.log(data);
});
}