c - `fork()` sons are executing in reverse order -


this question has answer here:

i have code similar this:

for (i = 0; < 3; i++) {     pid = fork();      if (pid == 0)     {         son_function();     }      if (pid < 0)     {         exit(1);     } }  void son_function(void) {     printf("my pid=%d\n", getpid());     printf("%d: alpha\n", getpid());     printf("%d: beta\n", getpid());     printf("%d: charlie\n", getpid());     exit(0); } 

for reason can't understand, order of execution of son_function() in reverse order. mean son_function() printing pid numbers largest smallest.

another thing freaks me prints every son in 1 after other, there's no way 2 prints 2 different processes print screen @ same time.

sample can seen here: http://ideone.com/ubyyrx

multiple processes can output console @ same time, @ least under windows , linux.

the reason may see of 1 process before of other due way particular os schedules threads. better way see behavior change son_function code below, each child sleeps different amount of time. reason lines interleaved (as noted before) because printf buffers lines of output.

void son_function() {     srandom(getpid());     int sleeptime = random() % 4; // random sleep between 0 , 3 seconds     printf("pid [%d] sleep time %d\n", getpid(), sleeptime);      printf("my pid = %d\n", getpid());     sleep(sleeptime);     printf("alpha = %d\n", getpid());     sleep(sleeptime);     printf("beta = %d\n", getpid());     sleep(sleeptime);     printf("charlie = %d\n", getpid());     sleep(sleeptime); } 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -