3

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.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
Alex
  • 133
  • 1
  • 10

1 Answers1

8

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.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thanks, but also in this case we need to use popen() in C/C++ program. I need to avoid using popen() – Alex May 05 '13 at 09:07
  • @Alex: You do not need `popen()` to access `/proc`, just use ordinary `open()` or `fopen()`. – Dietrich Epp May 05 '13 at 09:08
  • One more question. Can I read proc//proc if I don't have permissions to work with ? may be process of another owner. – Alex May 05 '13 at 09:14
  • Yes you can read the `/proc/1234/stat` of some process not belonging to you. – Basile Starynkevitch May 05 '13 at 09:17
  • Also if permissions of the executable are 700? And executable is not mine? – Alex May 05 '13 at 09:21
  • Yes, even for system processes not belonging to you the `/proc/1234/stat` file is *world* readable. And on some systems (e.g. SELinux) where you cannot read it, you should not care about that process (because you cannot do anything about it). – Basile Starynkevitch May 05 '13 at 09:25
  • It seemts that it works also if permissions of the executable are 700 and executable is not mine. Thanks – Alex May 05 '13 at 09:28