如何在 C 中使用等待 [英] how to use wait in C
问题描述
我如何使用 wait
?它只是让我不知所措.我 fork
一个带有递归的 procs 树,现在孩子们在我运行 pstree 时必须暂停(等待/睡眠),以便我可以打印 proc 树.
我应该使用
int 状态;等待(&状态);
或者更确切地说
wait(NULL)
我应该把它放在哪里?在父 if(pid > 0)
或子 if(pid==0)
中?也许在 ifs 的末尾,所以我将所有 pid
存储在数组中,然后对它们运行 for
并使用等待?
我的代码模板:
void ProcRec(int index){pid_t pid;int noChild = getNChild(index);国际我= 0;for(i = 0; i 0){/* 父进程 */}否则如果(pid == 0){/* 子进程.*/createProc(index+1);}别的{/* 错误 */退出(EXIT_FAILURE);}}if(getpid() == root){睡眠(1);pid = fork();如果(pid == 0)execl("/usr/bin/pstree", "pstree", getppid(), 0);}}
wait
系统调用使进程进入睡眠状态并等待子进程结束.然后用子进程的退出代码填充参数(如果参数不是NULL
).
所以如果在父进程中你有
int 状态;如果(等待(&状态)> = 0){如果(WEXITED(状态)){/* 子进程正常退出,通过 `return` 或 `exit` */printf("子进程退出,状态为 %d\n", WEXITSTATUS(status));}}
在子进程中,您执行例如exit(1)
,那么上面的代码就会打印
<小时>
还要注意等待所有子进程很重要.当父进程仍在运行时,您没有等待的子进程将处于所谓的僵尸状态,一旦父进程退出,子进程将被孤立并成为进程 1 的子进程.
How do i use wait
? It just baffles me to no end. I fork
a tree of procs with recursion and now the children have to pause(wait/sleep) while I run pstree so I can print the proc tree.
Should i use
int status;
wait(&status);
or rather
wait(NULL)
and where should i put this? in the parent if(pid > 0)
or in the children if(pid==0)
? Maybe at the end of ifs, so I store all the pid
s in array and then run a for
over them and use wait?
my code template:
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);
}
}
The wait
system-call puts the process to sleep and waits for a child-process to end. It then fills in the argument with the exit code of the child-process (if the argument is not NULL
).
So if in the parent process you have
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));
}
}
And in the child process you do e.g. exit(1)
, then the above code will print
Child process exited with 1 status
Also note that it's important to wait for all child processes. Child processes that you don't wait for will be in a so-called zombie state while the parent process is still running, and once the parent process exits the child processes will be orphaned and made children of process 1.
这篇关于如何在 C 中使用等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!