How the the output will be printed?

Viewed 56

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 ? I know it depends on the CPU and it might differ from one computer to another, but what will be the possible solutions ? Cuz I thought of 6 different orders of these statements may appear.

#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;
}
1 Answers

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. Therefore, any of the 4! = 24 orders are possible.

(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.)

While 24 orderings of the actual calls are possible, some of the messages are indistinguishable since they print the same text. There are two pairs of identical messages, so the number of distinguishable results is 24/2!/2! = 6.

Related