Why is rand() not so random after fork?

前端 未结 7 1182
星月不相逢
星月不相逢 2020-12-03 22:05
#include 
#include 
#include 
#include 

int main() {
    int i =10;
    /* initialize random seed:  */
         


        
7条回答
  •  被撕碎了的回忆
    2020-12-03 22:41

    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.

提交回复
热议问题