当前位置: 技术问答>linux和unix
一个父子进程、fork、waitpid的小问题
来源: 互联网 发布时间:2017-05-15
本文导语: 有这样一段代码: int main() { if(fork()==0){ print("a"); } else{ printf("b"); waitpid(-1, NULL, 0);} printf("c"); exit(0); } 请问可能的输入有哪些?(这是深入理解计算机系统第二版P497的一个习题) ...
有这样一段代码:
请问可能的输入有哪些?(这是深入理解计算机系统第二版P497的一个习题)
答案中说有四种可能,分别是
bacc
abcc
acbc
bcac
前三种我都能够想到,但是第四种真的能够发生吗?
我认为由于父进程执行waitpid函数,且第三个参数为0,因此在子进程终止后才能继续运行,也就是说,父进程的c不可能在a之前出现。
请问我是错的还是书中答案是错的?
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之前出现。
请问我是错的还是书中答案是错的?
|
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 的输出,看起来确实可能。
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 的输出,看起来确实可能。