在Ubuntu和其他类Unix系统中,僵尸进程(Zombie Process)是一种已经结束运行但尚未被其父进程回收资源的进程。僵尸进程的产生通常有以下几种情况:
当一个子进程结束时,操作系统会将其状态设置为EXIT_ZOMBIE
,并通知其父进程。如果父进程没有调用wait()
或waitpid()
函数来读取子进程的退出状态,子进程就会变成僵尸进程。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
printf("Child process exiting...\n");
exit(0);
} else if (pid > 0) {
// 父进程
printf("Parent process waiting for child...\n");
// 父进程没有调用wait()或waitpid()
sleep(10);
} else {
// fork失败
perror("fork");
exit(1);
}
return 0;
}
如果父进程在子进程结束之前退出,并且没有正确地重新父化(reparenting)子进程,子进程也会变成僵尸进程。通常,init进程(PID为1)会自动接管这些僵尸进程。
如果父进程因为某种原因崩溃或被杀死,而子进程还在运行,那么子进程将失去其父进程,变成僵尸进程。
在多线程程序中,如果主线程退出而没有正确地等待其他线程结束,这些线程可能会变成僵尸进程。
wait()
或waitpid()
函数来读取子进程的退出状态。wait()
或waitpid()
。fork()
和exec()
组合:在子进程中调用exec()
系列函数来替换当前进程映像,这样子进程就不会再有退出状态需要父进程处理。#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void sigchld_handler(int s) {
while (waitpid(-1, NULL, WNOHANG) > 0);
}
int main() {
struct sigaction sa;
pid_t pid;
// 设置SIGCHLD信号处理函数
sa.sa_handler = sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
pid = fork();
if (pid == 0) {
// 子进程
printf("Child process exiting...\n");
exit(0);
} else if (pid > 0) {
// 父进程
printf("Parent process waiting for child...\n");
while (1) {
sleep(1);
}
} else {
// fork失败
perror("fork");
exit(1);
}
return 0;
}
通过上述方法,可以有效地避免僵尸进程的产生。