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

javascript - How to synchronize the Three.js and HTML/SVG coordinate systems (especially w.r.t. the y-axis)? -

javascript - How do I find how many occurences are there of a highlighted string, and which occurence is it? -

java - Reading data from multiple zip files and combining them to one -