#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i =10;
/* initialize random seed: */
srand(time(NULL));
while(i--){
if(fork()==0){
/* initialize random seed here does not make a difference:
srand(time(NULL));
*/
printf("%d : %d\n",i,rand());
return;
}
}
return (EXIT_SUCCESS);
}
Prints the same (different on each run) number 10 times - expected ? I have a more complicated piece of code where each forked process runs in turn - no difference
The reason that even adding
srand(time(NULL));
(the line inside theif
block that you have commented) inside the loop isn't making a difference is because modern computers can execute that whole block extremely fast, andtime
counts in seconds. From the man pages:If you add a
sleep(1);
after theif
statement in thewhile
loop and uncomment thesrand
call, the results will be different, sincetime
would now return a different value because a second has elapsed.It would however be more appropriate to use a different seed value, rather than waiting. Something like
i
would be a good idea since it'll be unique for each iteration of the loop.