summaryrefslogtreecommitdiffstats
path: root/node_modules/pstree.remy/lib/tree.js
blob: bac7cce65cda9e39a45af6675853cba8c4414c0d (plain) (blame)
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
const spawn = require('child_process').spawn;

module.exports = function (rootPid, callback) {
  const pidsOfInterest = new Set([parseInt(rootPid, 10)]);
  var output = '';

  // *nix
  const ps = spawn('ps', ['-A', '-o', 'ppid,pid']);
  ps.stdout.on('data', (data) => {
    output += data.toString('ascii');
  });

  ps.on('close', () => {
    try {
      const res = output
        .split('\n')
        .slice(1)
        .map((_) => _.trim())
        .reduce((acc, line) => {
          const pids = line.split(/\s+/);
          const ppid = parseInt(pids[0], 10);

          if (pidsOfInterest.has(ppid)) {
            const pid = parseInt(pids[1], 10);
            acc.push(pid);
            pidsOfInterest.add(pid);
          }

          return acc;
        }, []);

      callback(null, res);
    } catch (e) {
      callback(e, null);
    }
  });
};