C语言 如何防止僵尸子进程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17015830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:39:07  来源:igfitidea点击:

How can I prevent zombie child processes?

cposixzombie-process

提问by thejh

I am writing a server that uses fork()to spawn handlers for client connections. The server does not need to know about what happens to the forked processes – they work on their own, and when they're done, they should just die instead of becoming zombies. What is an easy way to accomplish this?

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

采纳答案by thejh

There are several ways, but using sigactionwith SA_NOCLDWAITin the parent process is probably the easiest one:

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

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

回答by xaxxon

Use double forks. Have your children immediately fork another copy and have the original child process exit.

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

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

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

This is simpler than using signals, in my opinion, and more understandable.

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

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);
  }
}

回答by user3060336

How to get rid of zombie processes?

如何摆脱僵尸进程?

you can't kill the zombie process with SIGKILL signal as you kill a normall process, As the zombie process can't recive any signal. so having a good habit is very important.

您不能像杀死正常进程一样使用 SIGKILL 信号杀死僵尸进程,因为僵尸进程无法接收任何信号。所以养成一个好习惯很重要。

Then when programming, how to get rid amount of zombie processes? According to the above description, the child process will send SIGCHLD signals to the parent process when its dies. by default, this signal is ignored by system, so the best way is that we can call wait() in the signal processing function, which could avoid the zombie stick around in the system. see more about this: http://itsprite.com/how-to-deep-understand-the-zombie-process-in-linux/

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