【发布时间】:2015-11-08 12:35:40
【问题描述】:
我在 c 中有这个小程序,我试图了解它是如何工作的,它是一个简单的 while 循环,它使用 fork() 和 wait() 在命令行上打印出几行,我已经评论到尽我所能,我认为正在发生的事情
for (i = 1; i <= 3; i++) /*simple while loop, loops 3 times */
{
pid = fork(); /*returns 0 if a child process is created */
if(pid == 0){ /*pid should be a 0 for first loop */
printf("Hello!\n"); /*we print hello */
return (i); /*will this return i to the parent process that called fork? */
} else { /*fork hasn't returned 0? */
pid = wait(&j); /*we wait until j is available? */
printf("Received %d\n", WEXITSTATUS(j)); /*if available we print "received (j)" */
}
}
这个程序应该打印:
Hello!
Received 1
Hello!
Received 2
Hello!
Received 3
当其中一个子进程返回i 时,父进程是否以&j 等待它?这真的让我很困惑,任何帮助将不胜感激。
【问题讨论】:
-
fork()不是pthread_create(),因此调用fork()的函数中的returning 不一定会终止进程。发布所有的相关代码。 -
函数:fork() 有三种可能的返回状态,错误发生时为'-1',执行子时为'0',执行父时为某个正数。发布的代码未处理错误返回。
标签: c fork wait pid wexitstatus