小编ris*_*shi的帖子

为什么信号处理程序中的waitpid需要循环?

我在电子书中读到waitpid(-1,&status,WNOHANG)应该放在while循环中,这样如果多个子进程同时退出,它们都会被收获.

我通过同时创建和终止2个子进程并通过waitpid收到它而不使用循环来尝试这个概念.这些都被收获了.

问题是,将waitpid放在循环中是否非常必要?

#include<stdio.h>
#include<sys/wait.h>
#include<signal.h>

int func(int pid)
{
  if(pid < 0)
    return 0;
  func(pid - 1);
}

void sighand(int sig)
{
  int i=45;
  int stat, pid;
  printf("Signal caught\n");
  //while( (
  pid = waitpid(-1, &stat, WNOHANG);
  //) > 0){
  printf("Reaped process %d----%d\n", pid, stat);
  func(pid);
}

int main()
{
  int i;
  signal(SIGCHLD, sighand);
  pid_t child_id;

  if( (child_id=fork()) == 0 )  //child process
  {
    printf("Child  ID %d\n",getpid());
    printf("child exiting ...\n");
  }
  else
  {
    if( (child_id=fork()) == 0 ) //child process …
Run Code Online (Sandbox Code Playgroud)

c unix linux process

1
推荐指数
1
解决办法
686
查看次数

标签 统计

c ×1

linux ×1

process ×1

unix ×1