ps.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var os = require('os');
  3. var bin = require('./bin');
  4. /**
  5. * Gets the list of all the pids of the system through the ps command.
  6. * @param {Function} callback(err, list)
  7. */
  8. function ps(callback) {
  9. var args = ['-A', '-o', 'ppid,pid'];
  10. bin('ps', args, function(err, stdout, code) {
  11. if (err) return callback(err);
  12. if (code !== 0) {
  13. return callback(new Error('pidtree ps command exited with code ' + code));
  14. }
  15. // Example of stdout
  16. //
  17. // PPID PID
  18. // 1 430
  19. // 430 432
  20. // 1 727
  21. // 1 7166
  22. try {
  23. stdout = stdout.split(os.EOL);
  24. var list = [];
  25. for (var i = 1; i < stdout.length; i++) {
  26. stdout[i] = stdout[i].trim();
  27. if (!stdout[i]) continue;
  28. stdout[i] = stdout[i].split(/\s+/);
  29. stdout[i][0] = parseInt(stdout[i][0], 10); // PPID
  30. stdout[i][1] = parseInt(stdout[i][1], 10); // PID
  31. list.push(stdout[i]);
  32. }
  33. callback(null, list);
  34. } catch (error) {
  35. callback(error);
  36. }
  37. });
  38. }
  39. module.exports = ps;