【发布时间】:2014-04-21 07:14:36
【问题描述】:
我有一个难闻的问题:(
我有这个代码:
int main()
{
pid_t child, parent;
int status=0;
int i;
printf("parent = %d\n", getpid());
for(i=1; i<=5; i++){
if( (child = fork()) == 0){
sleep(i);
printf("i=%d, %d\n",i, getpid());
}
}
wait(0);
while( (parent = wait(&status)) > 0){
printf("Exit = %d, child = %d\n", status/256, parent);
}
}
输出类似于:
1, 21320
2, 21321
Exit = 0, child = 21321
3, 21322
Exit = 0, child = 21322
4, 21323
Exit = 0, child = 21323
5, 21324
Exit = 0, child = 21324
我认为 wait(0) 不等待所有子进程,而只等待第一次退出并写入所有 (Exit = ...)。
有没有办法做到这一点:
1, 21320
2, 21321
3, 21322
4, 21323
5, 21324
Exit = 0, child = 21320
Exit = 0, child = 21321
Exit = 0, child = 21322
Exit = 0, child = 21323
Exit = 0, child = 21324
?
【问题讨论】:
-
wait的手册说:“等待暂停调用进程,直到 一个 子进程结束。” -
这个
status/256很时髦。试试 WEXITSTATUS。而 `parent = wait()` 只是令人困惑。它(理想情况下)返回子 pid..