Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is rand() not so random after fork?

Tags:

c

fork

random

#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

like image 289
Mr_and_Mrs_D Avatar asked Dec 24 '11 06:12

Mr_and_Mrs_D


2 Answers

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.

like image 75
AusCBloke Avatar answered Oct 21 '22 14:10

AusCBloke


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.

like image 31
tangrs Avatar answered Oct 21 '22 13:10

tangrs