如何从fork()系统呼叫的父母和孩子之间输出彼此交织?

发布于 2025-01-22 18:44:42 字数 274 浏览 2 评论 0 原文

代码读取类似 :

pid=fork()
if(pid){
    print parent_id
    print parent_id
}
else{
    print child_id
    print child_id
}

执行时是 

child 
parent 
child 
parent

我不明白这是怎么发生的,因为应该连续打印孩子和父母。

code reads something like :

pid=fork()
if(pid){
    print parent_id
    print parent_id
}
else{
    print child_id
    print child_id
}

when it was executed it was 

child 
parent 
child 
parent

I don't understand how this could happen because child and parent should be printed consecutively.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

女中豪杰 2025-01-29 18:44:42

您可能有一个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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文