您需要使用proc(5) 文件系统。访问其中的文件(例如/proc/1234/stat ...)非常快(它不涉及任何物理 I/O)。
您可能想要来自/proc/1234/stat 的第三个字段(每个人都可以阅读,但您应该按顺序阅读,因为它是不可搜索的。)。如果该字段为Z,则 pid 1234 的进程是僵尸进程。
无需 fork 进程(例如 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 文件变成棘手。