如何在C中使用等待

我如何使用wait ? 它让我感到困惑不已。 我用递归来fork一个procs树,现在孩子们在我运行pstree时必须暂停(等待/hibernate),这样我就可以打印proc树了。

我应该用吗?

 int status; wait(&status); 

更确切地说

 wait(NULL) 

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

我的代码模板:

 void ProcRec(int index) { pid_t pid; int noChild = getNChild(index); int i= 0; for(i = 0; i  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); } } 

wait系统调用将进程置于hibernate状态并等待子进程结束。 然后它使用子进程的退出代码填充参数(如果参数不是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)); } } 

在子进程中,例如exit(1) ,然后打印上面的代码

子进程退出1状态

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

Interesting Posts