dynamo
dynamo

Reputation: 47

Content written before fork() present in output twice

I wrote the following C code:

#include<stdio.h>

int main(){
    printf("A");
    if(fork() == 0){
        printf("B");
    }
    else{
        printf("C");
    }
}

The output I got is:

ACAB

I expected this code to print A only once.
Can anyone explain this output?

Upvotes: 1

Views: 78

Answers (2)

Ed Heal
Ed Heal

Reputation: 59987

The 'A' is stored in a buffer and flushed by both processes when they exit.

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45654

Your error is not flushing the buffers before fork-ing, thus both processes will write it.

Add this before fork():

fflush(0); // Flush all output-streams

Upvotes: 3

Related Questions