bigC5012
bigC5012

Reputation: 599

Fork Program Output

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

int main(){
    int i;
    for(i=0;i<2;i++){
        fork();
        printf("%d\n", i);
    }
    return(0);
}

I am a little confused on the way fork works, to my understanding fork duplicates the memory including the stack, heap, static data, and text. I thought the program would return: 0 0 1 1 1 1 But I compiled and ran the program and the output is as follows: 0 1 0 1 1 1 Why is this?

Upvotes: 1

Views: 100

Answers (2)

Jay Dabhi
Jay Dabhi

Reputation: 58

The output will be random,because final answer depends on which process is finished at which time.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 476970

fork returns twice concurrently, i.e. at the same time.

Upvotes: 3

Related Questions