Linux僵尸进程(Zombie Process)是指已经结束运行但尚未被其父进程回收资源的子进程。僵尸进程的生命周期主要取决于其父进程是否正确地调用了wait()或waitpid()函数来回收子进程的资源。
以下是僵尸进程的生命周期:
exit()函数时,它会变成僵尸状态。wait()或waitpid()来获取子进程的退出状态,子进程就会保持僵尸状态。wait()或waitpid()来回收它。wait()或waitpid()并成功获取到子进程的退出状态后,子进程的资源会被释放,僵尸进程也就消失了。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 == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
printf("Child process (PID: %d) is running.\n", getpid());
// 模拟子进程工作
sleep(5);
printf("Child process (PID: %d) is exiting.\n", getpid());
exit(EXIT_SUCCESS);
} else {
// 父进程
int status;
printf("Parent process (PID: %d) is waiting for child process (PID: %d).\n", getpid(), pid);
waitpid(pid, &status, 0); // 等待子进程结束并回收资源
printf("Parent process (PID: %d) has collected the child process.\n", getpid());
}
return 0;
}
在这个示例中,父进程通过waitpid()函数等待子进程结束并回收其资源,从而避免了僵尸进程的产生。