如何防止僵尸子进程?

我正在编写一个服务器,它使用fork()为客户端连接生成处理程序。 服务器不需要知道分叉进程会发生什么 – 它们自己工作,当它们完成时,它们应该只是死而不是变成僵尸。 什么是实现这一目标的简单方法?

有几种方法,但在父进程中使用SA_NOCLDWAIT sigaction可能是最简单的方法:

 struct sigaction sigchld_action = { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDWAIT }; sigaction(SIGCHLD, &sigchld_action, NULL); 

使用双叉。 让您的孩子立即分叉另一个副本并让原始子进程退出。

http://thinkiii.blogspot.com/2009/12/double-fork-to-avoid-zombie-process.html

在我看来,这比使用信号更简单,更容易理解。

 void safe_fork() { pid_t pid; if (!pid=fork()) { if (!fork()) { /* this is the child that keeps going */ do_something(); /* or exec */ } else { /* the first child process exits */ exit(0); } } else { /* this is the original process */ /* wait for the first child to exit which it will immediately */ waitpid(pid); } } 

如何摆脱僵尸进程?

当你杀死一个正常的进程时,你不能用SIGKILL信号杀死僵尸进程,因为僵尸进程无法回复任何信号。 所以养成良好的习惯非常重要。

然后在编程时,如何摆脱僵尸进程的数量? 根据以上描述,子进程在其死亡时将向父进程发送SIGCHLD信号。 默认情况下,系统会忽略此信号,因此最好的方法是我们可以在信号处理函数中调用wait(),这样可以避免僵尸在系统中停留。 了解更多相关信息: http : //itsprite.com/how-to-deep-understand-the-zombie-process-in-linux/