Calling fork seemingly jumps back to the beginning of the program

I noticed that in this code, fork makes the program go back to the beginning rather than sort of keeping on.

#include <unistd.h>
#include <stdio.h>
#include <time.h>

int main(void) {
    int a = 10;
    printf("What??? ");
    int *b = &a;
    printf("%p\t", b);
    int tm = time(0);
    
    int f = fork();
    if (!f) *b = 15;
    else while(time(0) == tm);
    printf("%d %p\t", *b, b);
    
}

The output I expect is a single What???. The numbers are what I was initially trying to figure out, so I don’t have an expectation related to that. However, I get two What???s. An example of the current behavior is What??? 0x7fffd7120334 15 0x7fffd7120334 What??? 0x7fffd7120334 10 0x7fffd7120334

To make the code clearer, what I was writing was initially related to if forcing a variable to be a register when using concurrency would change anything.

I tried taking the fork call out of the condition (which is currently out), and I also tried using a block if that would somehow change anything.

>Solution :

The stream stdout is, by default, either line-buffered or fully buffered. Therefore, the line

printf("What??? ");

will likely put that string into the output buffer, without flushing it.

When you call fork, the output buffer is duplicated, so that when the output buffers of both processes are eventually flushed, that string is printed by both processes.

To prevent this from happening, you should flush the output buffer before the call to fork, for example by using the function call fflush( stdout );. If stdout is line-buffered (which is normally the case when connected to a terminal), inserting a newline character should also be sufficient.

Leave a Reply