您需要使用proc(5)文件系统.访问其中的文件(例如/ proc / 1234 / stat …)非常快(它不涉及任何物理I / O).
你可能想要/ proc / 1234 / stat中的第三个字段(每个人都可以读取,但是你应该按顺序读取它,因为它是不可见的.).如果该字段是Z,那么pid 1234的过程是僵尸.
无需分叉进程(例如withpopen或system),在C中你可能编写代码
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);
还要考虑procps和libproc,请参阅this answer.
(您还可以阅读/ proc / 1234 / status的第二行,但这可能更难以在C或C代码中解析)
顺便说一下,我发现/ proc /中的stat文件有一种奇怪的格式:如果你的可执行文件恰好在其名称中包含空格和括号(这很恶心,但允许),解析/ proc / * / stat文件变得棘手.