Skip to content

Commit e54650f

Browse files
committed
is_alive(): use new parse_proc_pid_stat() and fix zombie main thread case
Relates-to: #309
1 parent aa4753b commit e54650f

File tree

1 file changed

+6
-33
lines changed

1 file changed

+6
-33
lines changed

meminfo.c

Lines changed: 6 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "globals.h"
1616
#include "meminfo.h"
1717
#include "msg.h"
18+
#include "proc_pid.h"
1819

1920
/* Parse the contents of /proc/meminfo (in buf), return value of "name"
2021
* (example: "MemTotal:")
@@ -134,42 +135,14 @@ bool is_alive(int pid)
134135
return false;
135136
}
136137

137-
char buf[PATH_LEN] = { 0 };
138-
// Read /proc/[pid]/stat
139-
snprintf(buf, sizeof(buf), "%s/%d/stat", procdir_path, pid);
140-
FILE* f = fopen(buf, "r");
141-
if (f == NULL) {
142-
// Process is gone - good.
143-
return false;
144-
}
145-
146-
// File content looks like this:
147-
// 10751 (cat) R 2663 10751 2663[...]
148-
// File may be bigger than 256 bytes, but we only need the first 20 or so.
149-
memset(buf, 0, sizeof(buf));
150-
size_t len = fread(buf, 1, sizeof(buf), f);
151-
bool read_error = ferror(f) || len == 0;
152-
fclose(f);
153-
if (read_error) {
154-
warn("%s: fread failed: %s\n", __func__, strerror(errno));
155-
return false;
156-
}
157-
158-
// Find last ")" by searching from the end
159-
int i = sizeof(buf) - 1;
160-
for (; i >= 0; i--) {
161-
if (buf[i] == ')')
162-
break;
163-
}
164-
if (i <= 0 || i + 2 >= (int)sizeof(buf)) {
165-
warn("%s: could not find closing bracket\n", __func__);
138+
pid_stat_t stat;
139+
if(!parse_proc_pid_stat(&stat, pid)) {
166140
return false;
167141
}
168-
char state = buf[i + 2];
169142

170-
debug("process state: %c\n", state);
171-
if (state == 'Z') {
172-
// A zombie process does not use any memory. Consider it dead.
143+
debug("%s: state=%c num_threads=%ld\n", __func__, stat.state, stat.num_threads);
144+
if (stat.state == 'Z' && stat.num_threads == 1) {
145+
// A zombie process without subthreads does not use any memory. Consider it dead.
173146
return false;
174147
}
175148
return true;

0 commit comments

Comments
 (0)