如何从fork()系统呼叫的父母和孩子之间输出彼此交织?
代码读取类似 :
pid=fork()
if(pid){
print parent_id
print parent_id
}
else{
print child_id
print child_id
}
执行时是 
child
parent
child
parent
我不明白这是怎么发生的,因为应该连续打印孩子和父母。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能有一个mutli核CPU,因此父母和孩子都可以在单独的CPU内核上运行。打印足够缓慢,以至于父程流程有时间在您的孩子过程的第二次打印开始之前开始其第一印刷。
或者,如果没有,在单核机上,调度可以在一次打印后进行上下文切换。
fork
的全部要点是创建一个也正在运行的过程;不应该期望他们的系统调用不会相互交织。现有的关于叉竞赛条件 /时机的近乎建筑,尽管主要是运行首先< / strong>的那些,而不是任何期望继续在其他过程可以执行任何操作之前继续进行多个系统呼叫的期望。
并且更普遍地关于在父母和子女中进行多个系统调用,包括
读
,从而导致一个或两个阻塞。还有两个人遇到相反问题的地方:他们预期交错了产出,但没有得到。 (也许是由于I/O缓冲i/o仅导致一个
写入
系统调用,如果从IDE运行并连接到管道而不是TTY的IDE。)You probably have a mutli-core CPU, so both parent and child can both be running on separate CPU cores. Printing is slow enough that the parent process has time to gets its 1st print started before your child process's 2nd print starts.
Or if not, on a single-core machine then scheduling could context-switch after one print.
The whole point of
fork
is to create a 2nd process that's also running; there should be no expectation that their system calls don't interleave with each other.Existing near-duplicates about fork race conditions / timing, although those primarily about which runs first, not any expectation of continuing to run for multiple system calls before the other process can do anything.
And more generally Understanding parent and child process execution order about making multiple system calls including
read
in both parent and child, causing one or both to block.And two where people had the opposite problem: they expected interleaving of output but didn't get it. (Perhaps because of buffered I/O resulting in only one
write
system call, if run from an IDE with output connected to a pipe instead of tty perhaps.)