source: node_modules/pstree.remy/lib/utils.js

main
Last change on this file was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

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