如何在C中使用等待

The*_*red 7 c wait

我该怎么用wait?它让我感到困惑不已.我fork是一个带递归的触发树,现在孩子们必须暂停(等待/睡眠),而我运行pstree,这样我就可以打印proc树了.

我应该用吗?

int status;
wait(&status);
Run Code Online (Sandbox Code Playgroud)

更确切地说

wait(NULL)
Run Code Online (Sandbox Code Playgroud)

我应该把它放在哪里?在父母if(pid > 0)或孩子if(pid==0)?也许在ifs的末尾,所以我将所有pids 存储在数组中然后运行for它们并使用wait?

我的代码模板:

void ProcRec(int index)
{
     pid_t pid;
     int noChild = getNChild(index);

     int i= 0;
     for(i = 0; i < noChild; i++)
     { 
          pid = fork();

        if (pid > 0)
        {
            /* parent process */
        }
        else if (pid == 0)
        {
            /* child process. */
            createProc(index+1);
        }
        else
        {
            /* error */
            exit(EXIT_FAILURE);
        }
    }

    if(getpid() == root)
    {
        sleep(1); 
        pid = fork();
        if(pid == 0)
          execl("/usr/bin/pstree", "pstree", getppid(), 0);    
    }
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 11

wait系统调用使进程进入睡眠状态并等待一个子进程结束.然后它使用子进程的退出代码填充参数(如果参数不是NULL).

所以如果在父进程中你有

int status;
if (wait(&status) >= 0)
{
    if (WEXITED(status))
    {
        /* Child process exited normally, through `return` or `exit` */
        printf("Child process exited with %d status\n", WEXITSTATUS(status));
    }
}
Run Code Online (Sandbox Code Playgroud)

在子进程中,例如exit(1),上面的代码将打印出来

Child process exited with 1 status

另请注意,等待所有子进程非常重要.当父进程仍在运行时,您不等待的子进程将处于所谓的僵尸状态,一旦父进程退出,子进程将被孤立并成为进程1的子进程.

  • @ user2202368然后你不关心状态,你只是等待子进程退出. (2认同)