多进程编程中会可能会产生僵尸进程,这些僵尸进程不断蚕食系统资源,是系统变得越来越慢直至死亡,这种情况在并发模型中体现的尤为突出。这里分析下我们在多进程编程中如何解决这样的问题。
首先我们写一个例子:
#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查看发现原来程序运行过程僵尸态的子进程已经不在了。已经不在了。
Copyright © 2004-2024 华清远见教育科技集团 版权所有
京ICP备16055225号-5,京公海网安备11010802025203号