[英]Unexpected behavior when printf is used after fork() and the parent is on wait()
我有以下两组输出不同的代码。 【输出到终端】
代码 1:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main ()
{
printf("before the fork\n");
fflush(stdout);
int pid=fork();
printf("after the fork\n");
if (pid == 0)
{
sleep(1);
printf("I'm child");
}
else
{
wait();
printf ("I'm parent");
}
exit(0);
}
输出 1:
before the fork
after the fork
after the fork
I'm child
现在只有 fork 之后的 printf 被注释,我们看到父进程的 wait() 之后的 printf 按预期工作。
代码 2:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main ()
{
printf("before the fork\n");
fflush(stdout);
int pid=fork();
// printf("after the fork\n");
if (pid == 0)
{
sleep(1);
printf("I'm child");
}
else
{
wait();
printf ("I'm parent");
}
exit(0);
}
输出 2:
before the fork
I'm childI'm parent
我很困惑 fork() 之后的 printf 如何弄乱输出。
请注意以下输出
代码 3:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main ()
{
printf("before the fork\n");
fflush(stdout);
int pid=fork();
printf("after the fork\n");
if (pid == 0)
{
sleep(1);
printf("I'm child");
}
else
{
//wait();
printf ("I'm parent");
}
exit(0);
}
输出 3:
before the fork
after the fork
I'm parentafter the fork
I'm child
知道为什么会有这种差异吗?
这不是因为printf("after the fork\\n");
你得到不同的输出。
原因是当 fork() 系统调用被调用时,您会创建一个child process
。 并且parent process
和child process
都同时运行。 所以我们不知道哪个会获得优先权(可能是父母或孩子)。
在 code2 中,子进程获得了首选项,因此它首先执行,然后是父进程。
同样在代码 3 中,调用了 wait() 系统调用,因此如果父进程获得了优先级,它将一直执行到wait()
为止。 之后子进程被执行,子进程终止后,父进程从它离开的地方继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.