tree.js 738 B

1234567891011121314151617181920212223242526272829303132333435
  1. const spawn = require('child_process').spawn;
  2. module.exports = function(rootPid, callback) {
  3. const tree = {};
  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. if (line.indexOf(rootPid + ' ') === 0) {
  18. const pid = line.split(/\s+/).pop();
  19. acc.push(parseInt(pid, 10));
  20. rootPid = pid;
  21. }
  22. return acc;
  23. }, []);
  24. callback(null, res);
  25. } catch (e) {
  26. callback(e, null);
  27. }
  28. });
  29. };