我正在尝试编写一个shell,遇到了这个问题:在我运行fork()
并执行命令后,在主进程中,我等待所有子进程,如下所示:
while (wait(NULL) > 0);
但是当我尝试挂起子进程时,主进程不会通过此循环。
那么,如何仅等待非挂起的进程呢?我可以尝试保存所有已启动子进程的pid_t
,然后检查它们是否被挂起,但我认为也许有更好的方法。
要等待任何子项,无论是退出(也称为结束、终止(还是停止(也称为挂起(,请改用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()) */
}