Why is rand() not so random after fork?

The outputs must be the same. If two processes each seed the random number with the same seed and each call rand once, they must get the same result. That’s the whole point of having a seed. All of your processes call srand with the same seed (because you only call srand once) and they all call rand once, so they must get the same result.

Uncommenting the srand won’t make a difference because unless the number of seconds has changed, they will still give the same seed. You could do:

srand(time(NULL) ^ (getpid()<<16));

Leave a Comment