0

Can anyone explain why the line containing "here" is executed 5 times and how exactly the program runs because I don't seem to understand how I get this output

Output:

12958: 0 here
12959: 0
12958: 0 here
12958: 1 here
12960: 1
12958: 0 here
12958: 1 here

Code:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(){
    int i;
    for(i=0; i<2; i++){
        printf("%d: %d here\n", getpid(), i);
        if(fork()==0){
            printf("%d: %d\n", getpid(), i);
            exit(0);
        }
    }
    for(i=0; i<2; i++){
        wait(0);
    }
    return 0;
}

Edit: because I'm running windows on my computer I used this website link to check the code, could that be a problem?

Iulian Rosca
  • 1,005
  • 4
  • 15
  • 30
  • Running it using that website actually runs it on a *nix machine. – ooga Jun 27 '14 at 21:09
  • yes I know that, but I thought it's worth mentioning that it's not local – Iulian Rosca Jun 27 '14 at 21:11
  • Like ooga said it's something to do with output buffers. Here is a more detailed explanation http://stackoverflow.com/questions/2530663/printf-anomaly-after-fork – Yongzhi Jun 27 '14 at 21:28

2 Answers2

2

Fork creates an almost identical process, including the output buffers. If these are not flushed before the fork, both processes can end up printing the contents. Try putting a fflush(stdout); after the parent's printf.

ooga
  • 15,423
  • 2
  • 20
  • 21
0

It is not supposed to get the output you mentioned. As I tested your code my output was the following

11194: 0 here

11194: 1 here

11195: 0

11196: 1

Maybe you should recompile it and try again?

Yongzhi
  • 1,010
  • 1
  • 6
  • 13