多進程編程中父進程如何回收殭屍進程,經典中的經典

多進程編程中會可能會產生殭屍進程,這些殭屍進程不斷蠶食系統資源,是系統變得越來越慢直至死亡,這種情況在併發模型中體現的尤為突出。這裡分析下我們在多進程編程中如何解決這樣的問題。

首先我們寫一個例子:

#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;

}

本例中: 父進程創建子進程,進程完成移動工作後退出。運行效果如下:

this is parent process, pid = 3538

this is child process, pid = 3539

child process exit

使用ps -aux查看進程狀態

多進程編程中父進程如何回收殭屍進程,經典中的經典

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

多進程編程中父進程如何回收殭屍進程,經典中的經典

按照幫助文檔中說明:R為運行態,Z為殭屍(zombie)態。

回收殭屍進程我們可以用如下方法:

使用wait()或waitpid()函數。

#include

#include

pid_t wait(int *status);

pid_t waitpid(pid_t pid, int *status, int options);

wait: 父進程調用等待任一子進程退出。等同於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;

}

運行結果:

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查看發現原來程序運行過程殭屍態的子進程已經不在了。已經不在了。


分享到:


相關文章: