#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 the if block that you have commented) inside the loop isn't making a difference is because modern computers can execute that whole block extremely fast, and time counts in seconds. From the man pages:
time() returns the time as the number of seconds since the Epoch...
If you add a sleep(1); after the if statement in the while loop and uncomment the srand call, the results will be different, since time 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.
You're not reseeding when you make a child process. The state of the random number generator is exactly the same.
Even if you seed again in your child, you're seeding with the time with a +/- 1 second granularity. When you fork, it all happens in less than a second.
Try seeding it with something different and more random.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With