當(dāng)前位置:首頁 > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > 多進程編程中父進程如何回收僵尸進程,經(jīng)典中的經(jīng)典
多進程編程中父進程如何回收僵尸進程,經(jīng)典中的經(jīng)典
時間:2018-06-27 來源:未知
多進程編程中會可能會產(chǎn)生僵尸進程,這些僵尸進程不斷蠶食系統(tǒng)資源,是系統(tǒng)變得越來越慢直至死亡,這種情況在并發(fā)模型中體現(xiàn)的尤為突出。這里分析下我們在多進程編程中如何解決這樣的問題。
首先我們寫一個例子:
#include
#include
#include
int main(int argc, char **argv)
{
int pid;
pid = fork();
if (pid > 0) {
printf("this is parent process, pid = %d\n", getpid());
while(1);
} else if (pid == 0) {
printf("this is child process, pid = %d\n", getpid());
printf("child process exit\n");
} else {
printf("create child process failed\n");
}
return 0;
}
本例中: 父進程創(chuàng)建子進程,進程完成移動工作后退出。運行效果如下:
this is parent process, pid = 3538
this is child process, pid = 3539
child process exit
使用ps -aux查看進程狀態(tài)

此時父進程3538狀態(tài)為R+而子進程狀態(tài)為Z+,通過查看ps命令文檔可的如下說明:

回收僵尸進程我們可以用如下方法:
使用wait()或waitpid()函數(shù)。
#include
#include
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
wait: 父進程調(diào)用等待任一子進程退出。等同于waitpid(-1, &status, 0);
waitpid:
使用waitpid回收僵尸進程,如下:
C++ Code
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int pid, cpid;
pid = fork();
if (pid > 0) {
printf("this is parent process, pid = %d\n", getpid());
while(1) {
cpid = waitpid(-1, NULL, 0);
fprintf(stdout, "waitpid pid = %d: %s\n", cpid, strerror(errno));
sleep(1);
}
} else if (pid == 0) {
printf("this is child process, pid = %d\n", getpid());
printf("child process exit\n");
} else {
printf("create child process failed\n");
}
return 0;
}
運行結(jié)果:
this is parent process, pid = 4085
this is child process, pid = 4086
child process exit
waitpid pid = 4086: Success
waitpid pid = -1: No child processes
waitpid pid = -1: No child processes
ps -aux查看發(fā)現(xiàn)原來程序運行過程僵尸態(tài)的子進程已經(jīng)不在了。已經(jīng)不在了。

