utils.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const spawn = require('child_process').spawn;
  2. module.exports = { tree, pidsForTree, getStat };
  3. function getStat() {
  4. return new Promise((resolve) => {
  5. const command = `ls /proc | grep -E '^[0-9]+$' | xargs -I{} cat /proc/{}/stat`;
  6. const spawned = spawn('sh', ['-c', command], {
  7. stdio: ['pipe', 'pipe', 'pipe'],
  8. });
  9. var res = '';
  10. spawned.stdout.on('data', (data) => (res += data));
  11. spawned.on('close', () => resolve(res));
  12. });
  13. }
  14. function template(s) {
  15. var stat = null;
  16. // 'pid', 'comm', 'state', 'ppid', 'pgrp'
  17. // %d (%s) %c %d %d
  18. s.replace(
  19. /(\d+) \((.*?)\)\s(.+?)\s(\d+)\s/g,
  20. (all, PID, COMMAND, STAT, PPID) => {
  21. stat = { PID, COMMAND, PPID, STAT };
  22. }
  23. );
  24. return stat;
  25. }
  26. function tree(stats) {
  27. const processes = stats.split('\n').map(template).filter(Boolean);
  28. return processes;
  29. }
  30. function pidsForTree(tree, pid) {
  31. if (typeof pid === 'number') {
  32. pid = pid.toString();
  33. }
  34. const parents = [pid];
  35. const pids = [];
  36. tree.forEach((proc) => {
  37. if (parents.indexOf(proc.PPID) !== -1) {
  38. parents.push(proc.PID);
  39. pids.push(proc);
  40. }
  41. });
  42. return pids;
  43. }