Skip to content

Commit f97a652

Browse files
authored
Merge pull request #6 from Kf637/main
Add PID info command to fetch and display process details
2 parents 054f5d9 + 7c9de2d commit f97a652

1 file changed

Lines changed: 23 additions & 6 deletions

File tree

src/commands/pidinfo.js

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ async function fetchPidInfo(pid) {
7272
);
7373

7474
if (!match) {
75-
throw new Error("Unable to parse ps output");
75+
throw new Error(`Unable to parse ps output: "${truncate(line, 200)}"`);
7676
}
7777

7878
const [, parsedPid, ppid, user, cpu, mem, etime, cmd] = match;
@@ -118,7 +118,9 @@ async function fetchPidInfoBusybox(pid) {
118118
.match(/^(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/);
119119

120120
if (!match) {
121-
throw new Error("Unable to parse ps output");
121+
throw new Error(
122+
`Unable to parse ps output for PID ${pid}: ${truncate(row, 200)}`
123+
);
122124
}
123125

124126
const [, parsedPid, ppid, user, etime, cputime, _stat, cmd] = match;
@@ -196,10 +198,25 @@ async function readTotalJiffies() {
196198

197199
async function readProcJiffies(pid) {
198200
const stat = await fs.readFile(`/proc/${pid}/stat`, "utf8");
199-
const parts = stat.trim().split(/\s+/);
200-
const utime = Number(parts[13] || 0);
201-
const stime = Number(parts[14] || 0);
202-
const start = Number(parts[21] || 0);
201+
202+
// /proc/[pid]/stat format:
203+
// pid (comm) state ppid ... utime stime ... starttime ...
204+
// The comm field is in parentheses and can contain spaces, so we must
205+
// locate the closing ')' and only then split the remainder on whitespace.
206+
const endComm = stat.lastIndexOf(")");
207+
if (endComm === -1) {
208+
return { total: 0, start: 0 };
209+
}
210+
211+
const after = stat.slice(endComm + 1).trim().split(/\s+/);
212+
// After removing "pid (comm)", field indices shift by 2 positions.
213+
// Field 3 (state) becomes after[0], so:
214+
// - utime (field 14) -> after[11]
215+
// - stime (field 15) -> after[12]
216+
// - starttime (field 22) -> after[19]
217+
const utime = Number(after[11] || 0);
218+
const stime = Number(after[12] || 0);
219+
const start = Number(after[19] || 0);
203220
return { total: utime + stime, start };
204221
}
205222

0 commit comments

Comments
 (0)