一个父子进程、fork、waitpid的小问题

buaakq66 2014-04-10 05:11:33
有这样一段代码:

int main() 
{
if(fork()==0){
print("a");
}
else{
printf("b");
waitpid(-1, NULL, 0);}
printf("c");
exit(0);
}

请问可能的输入有哪些?(这是深入理解计算机系统第二版P497的一个习题)

答案中说有四种可能,分别是

bacc
abcc
acbc
bcac

前三种我都能够想到,但是第四种真的能够发生吗?

我认为由于父进程执行waitpid函数,且第三个参数为0,因此在子进程终止后才能继续运行,也就是说,父进程的c不可能在a之前出现。

请问我是错的还是书中答案是错的?
...全文
222 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhxianbin 2014-04-10
  • 打赏
  • 举报
回复
All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal. In the case of a terminated child, performing a wait allows the system to release the resources associated with the child; if a wait is not performed, then the terminated child remains in a "zombie" state (see NOTES below). If a child has already changed state, then these calls return immediately. Otherwise they block until either a child changes state or a signal handler interrupts the call (assuming that system calls are not automatically restarted using the SA_RESTART flag of sigaction(2)). In the remainder of this page, a child whose state has changed and which has not yet been waited upon by one of these system calls is termed waitable. 以上是 man waitpid 的输出,看起来确实可能。

3,286

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 实用资料发布区
社区管理员
  • 实用资料发布区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧