| [81bc7da] | 1 | const spawn = require('child_process').spawn;
|
|---|
| 2 |
|
|---|
| 3 | module.exports = { tree, pidsForTree, getStat };
|
|---|
| 4 |
|
|---|
| 5 | function 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 |
|
|---|
| 18 | function 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 |
|
|---|
| 32 | function tree(stats) {
|
|---|
| 33 | const processes = stats.split('\n').map(template).filter(Boolean);
|
|---|
| 34 |
|
|---|
| 35 | return processes;
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | function 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 | }
|
|---|