當(dāng)前位置:首頁(yè) > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > 多進(jìn)程編程中父進(jìn)程如何回收僵尸進(jìn)程,經(jīng)典中的經(jīng)典
多進(jìn)程編程中會(huì)可能會(huì)產(chǎn)生僵尸進(jìn)程,這些僵尸進(jìn)程不斷蠶食系統(tǒng)資源,是系統(tǒng)變得越來(lái)越慢直至死亡,這種情況在并發(fā)模型中體現(xiàn)的尤為突出。這里分析下我們?cè)诙噙M(jìn)程編程中如何解決這樣的問(wèn)題。
首先我們寫(xiě)一個(gè)例子:
#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;
}
本例中: 父進(jìn)程創(chuàng)建子進(jìn)程,進(jìn)程完成移動(dòng)工作后退出。運(yùn)行效果如下:
this is parent process, pid = 3538
this is child process, pid = 3539
child process exit
使用ps -aux查看進(jìn)程狀態(tài)
此時(shí)父進(jìn)程3538狀態(tài)為R+而子進(jìn)程狀態(tài)為Z+,通過(guò)查看ps命令文檔可的如下說(shuō)明:
回收僵尸進(jìn)程我們可以用如下方法:
使用wait()或waitpid()函數(shù)。
#include
#include
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
wait: 父進(jìn)程調(diào)用等待任一子進(jìn)程退出。等同于waitpid(-1, &status, 0);
waitpid:
使用waitpid回收僵尸進(jìn)程,如下:
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;
}
運(yùn)行結(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)原來(lái)程序運(yùn)行過(guò)程僵尸態(tài)的子進(jìn)程已經(jīng)不在了。已經(jīng)不在了。