Why is rand() not so random after fork?

2020-01-29 18:06发布

#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

标签: c random fork
7条回答
Luminary・发光体
2楼-- · 2020-01-29 18:40

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.

查看更多
登录 后发表回答