多(duo)進(jin)程(cheng)編程(cheng)中(zhong)父進(jin)程(cheng)如何回收僵(jiang)尸進(jin)程(cheng),經典中(zhong)的經典
時間:2018-06-27 來源:未知
多進(jin)(jin)程(cheng)編程(cheng)中(zhong)會可能(neng)會產生僵尸進(jin)(jin)程(cheng),這(zhe)些僵尸進(jin)(jin)程(cheng)不斷蠶食系統資源,是系統變得越來(lai)越慢直(zhi)至死亡,這(zhe)種(zhong)情況在(zai)并(bing)發模型中(zhong)體(ti)現的(de)尤為突出。這(zhe)里分(fen)析下我們在(zai)多進(jin)(jin)程(cheng)編程(cheng)中(zhong)如(ru)何解決這(zhe)樣的(de)問題。
首(shou)先我(wo)們(men)寫一個(ge)例(li)子:
#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;
}
本例中: 父進程創建(jian)子進程,進程完成(cheng)移動工作后退出。運行效果如下:
this is parent process, pid = 3538
this is child process, pid = 3539
child process exit
使用ps -aux查看進程狀(zhuang)態

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

回收僵尸進(jin)程我們(men)可(ke)以用如下方(fang)法:
使(shi)用wait()或waitpid()函數。
#include
#include
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
wait: 父進程調用(yong)等待(dai)任(ren)一子進程退出。等同于(yu)waitpid(-1, &status, 0);
waitpid:
使用waitpid回收僵尸(shi)進(jin)程,如下:
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;
}
運行結果:
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查看發(fa)現原(yuan)來(lai)程序運行(xing)過程僵尸態的(de)子進(jin)程已經不(bu)在了。已經不(bu)在了。

