在 CentOS 系統中,避免僵尸進程的方法有以下幾種:
wait()
或 waitpid()
函數:在父進程中使用 wait()
或 waitpid()
函數等待子進程結束。這樣可以確保子進程在退出時被正確地回收,避免僵尸進程的產生。#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子進程
// ... 執行任務 ...
exit(0);
} else if (pid > 0) {
// 父進程
int status;
waitpid(pid, &status, 0); // 等待子進程結束并回收資源
} else {
// 錯誤處理
}
return 0;
}
SIGCHLD
信號設置一個處理器,當子進程退出時,系統會發送 SIGCHLD
信號給父進程。在信號處理器中調用 wait()
或 waitpid()
函數回收子進程資源。#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void sigchld_handler(int signo) {
int status;
pid_t pid;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
printf("子進程 %d 結束\n", pid);
}
}
int main() {
struct sigaction sa;
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_t pid = fork();
if (pid == 0) {
// 子進程
// ... 執行任務 ...
exit(0);
} else if (pid > 0) {
// 父進程
// ... 執行其他任務 ...
} else {
// 錯誤處理
}
return 0;
}
fork()
和 exec()
組合:在創建子進程后,立即調用 exec()
函數族中的一個函數(如 execl()
、execp()
等)來替換子進程的內存空間。這樣,子進程就不會執行任何其他代碼,從而避免了僵尸進程的產生。#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子進程
char *argv[] = {"./your_executable", NULL};
execvp(argv[0], argv); // 替換子進程內存空間
perror("execvp"); // 如果 execvp 返回,說明出錯了
exit(1);
} else if (pid > 0) {
// 父進程
// ... 執行其他任務 ...
} else {
// 錯誤處理
}
return 0;
}
總之,要避免僵尸進程,關鍵是確保父進程在子進程退出時正確地回收其資源??梢酝ㄟ^使用 wait()
、waitpid()
函數或者信號處理器來實現這一目標。