避免产生僵尸进程的N种方法(zombie process)
注意:
1、如果僵尸进程已经产生,当其父进程终止时,僵尸进程还是会消失。
避免产生僵尸进程的5种方法:
1、最佳方法:fock twice, 用孙子进程去完成子进程的任务(http://blog.csdn.net/duyiwuer2009/article/details/7948040)
2、wait(), 但是会使父进程阻塞
3、signal(SIGCHLD,SIG_IGN), 并不是所有系统都兼容
4、sigaction + SA_NOCLDWAIT, 并不是所有系统都兼容
5、在signal handler中调用wait,这样父进程不用阻塞
关于对处理SIGCHLD或SIGCLD的讨论,APUE 10.7(http://infohost.nmt.edu/~eweiss/222_book/222_book.html) 是最权威最经典的,不过可能由于书出得较早,考虑了太多老系统,当时的系统对信号的处理还不是很完善,使得书中对这个问题的讨论显得相当复杂,但对于现在的系统,我们可以简化许多。
方法4的代码:
#include <signal.h>#include <stdlib.h>#include <stdio.h>#include <unistd.h>int main(){ pid_t pid; struct sigaction sa; /* prevent zombies */ sa.sa_handler = SIG_IGN; sa.sa_flags = SA_NOCLDWAIT; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } if( (pid = fork()) < 0 ) { exit(1); } else if(pid == 0) { sleep(10); exit(0); } sleep(20); return 0;}笔者所用系统的内核版本是2.6.38-8,方法3和方法4都支持【参考资料】
http://topic.csdn.net/u/20090911/16/5860C371-DBF9-440A-851B-C6AD26B6E480.html
http://baike.baidu.com/view/758736.htm
线程和进程的分离,http://blog.chinaunix.net/space.php?uid=317451&do=blog&id=92626
How do I get rid of zombie processes that persevere, http://www.faqs.org/faqs/unix-faq/faq/part3/section-13.html
http://www.ccur.com/isdfaq/How_do_I_avoid_creating_zombies.txt