tree.js 857 B

12345678910111213141516171819202122232425262728293031323334353637
  1. const spawn = require('child_process').spawn;
  2. module.exports = function (rootPid, callback) {
  3. const pidsOfInterest = new Set([parseInt(rootPid, 10)]);
  4. var output = '';
  5. // *nix
  6. const ps = spawn('ps', ['-A', '-o', 'ppid,pid']);
  7. ps.stdout.on('data', (data) => {
  8. output += data.toString('ascii');
  9. });
  10. ps.on('close', () => {
  11. try {
  12. const res = output
  13. .split('\n')
  14. .slice(1)
  15. .map((_) => _.trim())
  16. .reduce((acc, line) => {
  17. const pids = line.split(/\s+/);
  18. const ppid = parseInt(pids[0], 10);
  19. if (pidsOfInterest.has(ppid)) {
  20. const pid = parseInt(pids[1], 10);
  21. acc.push(pid);
  22. pidsOfInterest.add(pid);
  23. }
  24. return acc;
  25. }, []);
  26. callback(null, res);
  27. } catch (e) {
  28. callback(e, null);
  29. }
  30. });
  31. };