等待所有子进程避免挂起的进程

时间:2018-01-08 16:11:05

标签: c subprocess signals waitpid

我正在尝试编写一个shell,但我遇到了这个问题:运行fork()并执行命令后,在主进程中我等待所有这些子进程:

while (wait(NULL) > 0);

但是当我尝试暂停子进程时,主进程不会超过这个循环。

那我该如何只等待非暂停的进程呢? 我可以尝试保存所有已启动子流程的pid_t,然后检查它们是否被暂停,但我想也许有更好的方法。

1 个答案:

答案 0 :(得分:1)

要等待任何孩子,要么退出(也就是结束,终止)或停止(也就是暂停),请改用waitpid()

int wstatus;

{
  pid_t result;

  while (result = waitpid(-1, &wstatus, WUNTRACED)) /* Use WUNTRACED|WCONTINUED 
                                      to return on continued children as well. */
  {
    if ((pid_t) -1 = result)
    {
      if (EINTR = errno)
      {
        continue;
      }

      if (ECHILD == errno)
      {
        exit(EXIT_SUCCESS); /* no children */
      }

      perror("waitpid() failed");

      exit(EXIT_FAILURE);
    }
  }
}

if (WEXITED(wstatus))
{
  /* child exited normally with exit code rc = ... */
  int rc = WEXITSTATUS(wstatus);
  ...
}
else if (WIFSIGNALED(wstatus)
{
  /* child exited by signal sig = ... */
  int sig = WTERMSIG(wstatus);
  ...
}
else if (WSTOPPED(wstatus))
{
  /* child stopped by signal sig = ... */
  int sig = WSTOPSIG(wstatus);
  ...
}
else if (WCONTINUED(wstatus))
{
  /* child continued (occurs only if WCONTINUED was passed to waitpid()) */
}