Why is rand() not so random after fork?

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

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


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 22:37

    The rand() function is a pseudo-random number generator. This means that the sequence of numbers generated is deterministic, depending only upon the seed provided.

    Because you are forking the same process 10 times, the state of the random number generator is the same for each child. The next time you call rand() you will get the same value.

    By calling srand(time(NULL)) inside the child process, you are potentially helping but the granularity of time() is only 1 second, so all your children probably start inside the same second. Seeding with the same value generates the same pseudo-random sequence.

    You could try seeding with a value that depends on the child number:

    srand(time(NULL) - i*2);
    

    (I used i*2 in the event that time() advances by 1 second during the fork loop.)

提交回复
热议问题