Alex
Alex

Reputation: 133

Detect if pid is zombie on Linux

We can detect if some is a zombie process via shell command line

ps ef -o pid,stat | grep <pid> | grep Z

To get that info in our C/C++ programs we use popen(), but we would like to avoid using popen(). Is there a way to get the same result without spawning additional processes?

We are using Linux 2.6.32-279.5.2.el6.x86_64.

Upvotes: 3

Views: 2769

Answers (1)

You need to use the proc(5) filesystem. Access to files inside it (e.g. /proc/1234/stat ...) is really fast (it does not involve any physical I/O).

You probably want the third field from /proc/1234/stat (which is readable by everyone, but you should read it sequentially, since it is unseekable.). If that field is Z then process of pid 1234 is zombie.

No need to fork a process (e.g. withpopen or system), in C you might code

pid_t somepid;
// put the process pid you are interested in into somepid

bool iszombie = false;
// open the /proc/*/stat file
char pbuf[32];
snprintf(pbuf, sizeof(pbuf), "/proc/%d/stat", (int) somepid);
FILE* fpstat = fopen(pbuf, "r");
if (!fpstat) { perror(pbuf); exit(EXIT_FAILURE); };
{
  int rpid =0; char rcmd[32]; char rstatc = 0;
  fscanf(fpstat, "%d %30s %c", &rpid, rcmd, &rstatc); 
  iszombie = rstatc == 'Z';
}
fclose(fpstat);

Consider also procps and libproc so see this answer.

(You could also read the second line of /proc/1234/status but this is probably harder to parse in C or C++ code)

BTW, I find that the stat file in /proc/ has a weird format: if your executable happens to contain both spaces and parenthesis in its name (which is disgusting, but permitted) parsing the /proc/*/stat file becomes tricky.

Upvotes: 8

Related Questions