跟踪子进程死亡 [英] Tracking the death of a child process

查看:111
本文介绍了跟踪子进程死亡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何能跟踪一个子进程的死亡未做父进程等到子进程被杀害的?

How could I track down the death of a child process without making the parent process wait until the child process got killed?

我试图其中服务器接收来自客户端和叉为每个连接它接受一个新的进程的连接的客户端 - 服务器的场景。

I am trying a client-server scenario where the server accepts the connection from a client and forks a new process for each and every connection it accepts.

我忽略SIGCHLD信号,以prevent僵尸创建。

I am ignoring SIGCHLD signals to prevent zombie creation.

signal(SIGCHLD, SIG_IGN);
while(1)
{
  accept();
  clients++;
  if(fork() ==0)
  {
     childfunction();
     clients--;
  }
  else
  {
  }
}

在上述情况下的问题是,如果子进程得到了 childfunction杀死()函数,全局变量客户是没有得到减少。

The problem in the above scenario is that if the child process gets killed in the childfunction() function, the global variable clients is not getting decremented.

注意:我要寻找一个解决方案,而无需使用SIGCHLD信号......如果可能的话

NOTE: I am looking for a solution without using SIGCHLD signal ... If possible

推荐答案

通常你写 SIGCHLD 的处理程序这就要求 waitpid函数()的PID 1 。您可以使用从返回值,以确定哪些PID死亡。例如:

Typically you write a handler for SIGCHLD which calls waitpid() on pid -1. You can use the return value from that to determine what pid died. For example:

void my_sigchld_handler(int sig)
{
    pid_t p;
    int status;

    while ((p=waitpid(-1, &status, WNOHANG)) != -1)
    {
       /* Handle the death of pid p */
    }
}

/* It's better to use sigaction() over signal().  You won't run into the
 * issue where BSD signal() acts one way and Linux or SysV acts another. */

struct sigaction sa;

memset(&sa, 0, sizeof(sa));
sa.sa_handler = my_sigchld_handler;

sigaction(SIGCHLD, &sa, NULL);

另外,您可以拨打 waitpid函数(PID,和放大器;状态,0)与指定的子进程ID,并同步等待它死了。或者使用 WNOHANG 来检查其状态不阻塞。

Alternatively you can call waitpid(pid, &status, 0) with the child's process ID specified, and synchronously wait for it to die. Or use WNOHANG to check its status without blocking.

这篇关于跟踪子进程死亡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆