多進程編程中會可能會產生僵尸進程,這些僵尸進程不斷蠶食系統資源,是系統變得越來越慢直至死亡,這種情況在并發模型中體現的尤為突出。這里分析下我們在多進程編程中如何解決這樣的問題。
首先我們寫一個例子:
#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命令文檔可的如下說明:
回收僵尸進程我們可以用如下方法:
使用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查看發現原來程序運行過程僵尸態的子進程已經不在了。已經不在了。