简体   繁体   中英

C Fork program output explanation

I have a program in C which utilizes the fork() system call:

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

void doit(void)
{
    pid_t pid;
    fork();
    fork();
    printf("Unix System Programming\n");
    return;
}

int main(void)
{
    doit();
    printf("WTF\n");
    exit(0);
}

Now, this program gives me 8 lines of output. I think that is because of two forks 2^2 = 4 Times * 2 Print Statement = 8 Times. If I am wrong, please correct me and explain why.

Now, the question is why am I getting different outputs on each run? Let's say I execute this code: the first time I get output

Unix System Programming
WTF
Unix System Programming
Unix System Programming
Unix System Programming
WTF
WTF
WTF

and the 2nd time I get:

Unix System Programming
WTF
Unix System Programming
Unix System Programming
WTF
Unix System Programming
WTF
WTF

And third time again different. Why does this happen? I am clueless; kindly explain in detail.

When you fork a new process, the parent and child both run concurrently. The order that they execute their respective printf() statements is unpredictable -- sometimes the parent will print first, sometimes the child will.

You might understand better if you included the PID in the output, so you could see which process is printing each line. SO change it to:

printf("%d: Unix System Programming\n", getpid());

and

printf("%d: WTF\n", getpid());

What you should see is that each process prints Unix System Programming before WTF , but the order of processes will be mixed up.

The outputs that you are seeing are from different processes. Once fork has succeeded, you get a different child process (as well as the parent process). Since they are from different processes, you can't guarantee when one process gets its turn and executes. So the outputs of different processes get intermixed and the order might be different at each run.

If you want to make sure that parent and child processes run in some specific order then you have to synchronize them, which is typically a lot more work than just forking. (It will probably require a wait operation or the use of pipes — depending on the nature of synchronization that you want.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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