- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有这个简单的测试:
int main() {
int res = fork();
if (res == 0) { // child
printf("Son running now, pid = %d\n", getpid());
}
else { // parent
printf("Parent running now, pid = %d\n", getpid());
wait(NULL);
}
return 0;
}
当我运行它一百次时,即运行这个命令,
for ((i=0;i<100;i++)); do echo ${i}:; ./test; done
我得到:
0:
Parent running now, pid = 1775
Son running now, pid = 1776
1:
Parent running now, pid = 1777
Son running now, pid = 1778
2:
Parent running now, pid = 1779
Son running now, pid = 1780
等等;而当我第一次写入文件然后然后读取文件时,即运行这个命令,
for ((i=0;i<100;i++)); do echo ${i}:; ./test; done > forout
cat forout
我明白了!也就是说,
0:
Son running now, pid = 1776
Parent running now, pid = 1775
1:
Son running now, pid = 1778
Parent running now, pid = 1777
2:
Son running now, pid = 1780
Parent running now, pid = 1779
我知道调度程序。就 fork 后谁先运行而言,这个结果不意味着什么? fork 函数 do_fork()
(位于 kernel/fork.c
)以将 need_resched
标志设置为 1 结束,内核注释开发人员说,“让子进程先运行。”
我猜测这与 printf 写入的缓冲区有关。
此外,输入重定向 (>
) 会先将所有内容写入缓冲区,然后再复制到文件,这样说对吗?即便如此,为什么这会改变打印品的顺序?
注意:我正在一个单核虚拟机上运行测试,该虚拟机具有 Linux 内核 v2.4.14。
感谢您的宝贵时间。
最佳答案
当您重定向时,glibc 检测到 stdout 不是 tty 打开输出缓冲以提高效率。因此,在进程退出之前不会写入缓冲区。你可以看到这个,例如:
int main() {
printf("hello world\n");
sleep(60);
}
当您以交互方式运行它时,它会打印“hello world”并等待。当您重定向到一个文件时,您会看到 60 秒内没有任何内容写入:
$ ./foo > file & tail -f file
(no output for 60 seconds)
由于您的父进程等待子进程,它必然总是最后退出,因此最后刷新其输出。
关于linux - 谁先跑叉,结果相互矛盾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53600707/
我使用 docker save : > image.rar 导出图像,然后使用 docker import image.rar 将其导入另一个系统。 我可以在运行 docker image ls 时看
我不知道我的设置有什么问题: siegfried@ubuntu:~/chef-repo$ knife ssh -a ipaddress 'name:chefnode' 'uptime'
我有 Pig 脚本和用 Node.js 编写的示例应用程序。我只想从 Node.js 运行 Pig 脚本。 最佳答案 我没有使用过 node.js。但在这里我找到了一个链接来展示如何在 node.js
我正在为需要使用 distutils.extension 编译的某些代码构建docker镜像。我有一个运行python setup.py build_ext --inplace的Makefile。 我
我是一名优秀的程序员,十分优秀!