【问题标题】:Wait for all child processes avoiding the suspended processes等待所有子进程避免挂起的进程
【发布时间】:2018-01-08 16:11:04
【问题描述】:

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

while (wait(NULL) > 0);

但是当我尝试挂起子进程时,主进程不会经过这个循环。

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

【问题讨论】:

  • 这有帮助吗? linux.die.net/man/2/wait 我的意思是,只要孩子改变它的状态并返回一个 pid_t,它就会“唤醒”,应该可以工作,还没有测试过。
  • @punkkeks ty,但我已经读过这个人,但我真的找不到答案
  • waitpid() 让您可以更好地控制等待的内容。您正在寻找的可能是WNOHANG
  • @JonathanLeffler 是的,我想我会先保存 pid_t 的子进程,然后将 waitpid() 保存为非暂停进程,不知何故......
  • 不确定您的措辞。 “suspended”会是“stopped”(可以是“continued”)还是“ended”(“terminated”、“dead”)?

标签: c subprocess signals waitpid


【解决方案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()) */
}

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多