c - 在 fork() 之后使用 printf 并且父进程处于 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()
. 之后子进程被执行并且子进程终止后,父进程从它离开的地方继续。
推荐阅读
- python - sqlite3函数CREATE TABLE AS SELECT、MAX、CASE、AS如何配合使用?
- c - Linux 内核 filp_open 失败并显示 NOENT
- api - 如何防止 HERE MAPS / [Here-API] 过期?
- python - 为什么在使用 Google Vision 时出现列表索引超出范围错误?
- resque - 使用 DataDog 记录 ActiveJob APM 跟踪
- java - DateTimeParseException - 无法在索引 0 处解析文本“2020 年 8 月 19 日”
- forms - 提交按钮会覆盖 PowerApps 中 Excel 表中先前填充的行吗?
- swift - lldb 如何处理特殊用途的 _swift_runtime_on_report 函数?
- python - Pandas 合并和后缀
- r - 如何有条件地在分组数据中创建行