在CentOS系统中,僵尸进程是指子进程已经结束,但其父进程没有正确回收其资源,导致子进程的进程描述符仍然保留在系统中。以下是修复CentOS僵尸进程的几种方法:
wait()
或 waitpid()
在父进程中,确保在子进程结束后调用 wait()
或 waitpid()
来回收子进程的资源。以下是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
} else if (pid == 0) { // 子进程
printf("Child process is running
");
sleep(2);
printf("Child process is exiting
");
exit(0);
} else { // 父进程
printf("Parent process is waiting for child
");
wait(NULL); // 等待子进程结束
printf("Parent process is exiting
");
}
return 0;
}
如果父进程无法立即调用 wait()
,可以通过设置信号处理函数来捕获 SIGCHLD
信号,并在信号处理函数中调用 wait()
。以下是一个示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
void sigchld_handler(int signo) {
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
printf("Child process %d terminated
", pid);
}
}
int main() {
signal(SIGCHLD, sigchld_handler);
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
} else if (pid == 0) { // 子进程
printf("Child process is running
");
sleep(2);
printf("Child process is exiting
");
exit(0);
} else { // 父进程
printf("Parent process is running
");
while (1) {
sleep(1);
}
}
return 0;
}
如果父进程已经无法正常工作,或者你无法修改父进程的代码,可以考虑杀死父进程。当父进程被杀死后,僵尸进程会被 init
进程(PID为1)接管并回收。
kill -9 <父进程ID>
lsof
命令查找和清理僵尸进程lsof
命令可以用来查找和清理僵尸进程。以下是具体步骤:
安装 lsof
(如果尚未安装):
yum install lsof
查找僵尸进程:
lsof -n | grep deleted
杀死僵尸进程:
kill -9 $(lsof -n | grep deleted | awk '{print $2}')
如果系统中有多个僵尸进程,可以使用以下命令批量清理:
ps -A -o stat,ppid,pid,cmd | grep -e '[Zz]' | awk '{print $2}' | xargs kill -9