简体   繁体   English

输出将如何打印?

[英]How the the output will be printed?

i was doing some tracing on this code and it ended with printing 4 statements, 2 for parent and 2 for child but I am wondering how the order will be ?我正在对这段代码进行一些跟踪,它以打印 4 条语句结束,2 条用于父级,2 条用于子级,但我想知道顺序如何? I know it depends on the CPU and it might differ from one computer to another, but what will be the possible solutions ?我知道这取决于 CPU,并且可能因一台计算机而异,但可能的解决方案是什么? Cuz I thought of 6 different orders of these statements may appear.因为我想到了这些语句的 6 种不同顺序可能会出现。

#include <stdio.h>
#include <sys/types.h> #include <unistd.h>

void forkExample()
{
    int z = 8;

    if (fork() == 0)
    {
        fork();
        printf("Child with z = %d\n", ++z);
    }
    else
    {
        fork();
        printf("Parent with z = %d\n", --z);
    }
}

int main()
{
    forkExample(); return 0;
}

There is no sequencing between any of the printf calls—nothing in the code causes any of them in any process to come before or after any other.任何printf调用之间没有顺序——代码中的任何内容都不会导致任何进程中的任何调用出现在任何其他调用之前或之后。 Therefore, any of the 4!因此,任何4! = 24 orders are possible. = 24 个订单是可能的。

(This assumes each output is printed fully before another starts. This is not guaranteed by C or Posix/Unix but is likely with short texts using default buffer settings.) (这假设每个输出在另一个开始之前完全打印。C 或 Posix/Unix 不能保证这一点,但可能使用默认缓冲区设置的短文本。)

While 24 orderings of the actual calls are possible, some of the messages are indistinguishable since they print the same text.虽然可以对实际调用进行 24 次排序,但有些消息无法区分,因为它们打印的是相同的文本。 There are two pairs of identical messages, so the number of distinguishable results is 24/2!/2!有两对相同的消息,因此可区分结果的数量是 24/2!/2! = 6. = 6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM