process - Understanding unix fork -


can explain why line containing "here" executed 5 times , how program runs because don't seem understand how 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 computer used website link check code, problem?

fork creates identical process, including output buffers. if these not flushed before fork, both processes can end printing contents. try putting fflush(stdout); after parent's printf.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -