Seeding random number generator for a batch of programs
c, random
Solution
Use `srand(time(0) ^ getpid())` to permute your seed by a process-specific value. This will ensure different seeds for processes started within the same second. Take care to not use this for anything "important", e.g., cryptography or real money is involved.
The permutation is accomplished using the "exclusive-or" or XOR operator '^'. Because we know that two process running at the same time must necessarily have different process-ids, by xoring the response from time(0) with the current PID, we can get some assurance that two different processes won't have exactly the same seed.
Note that this is a very weak assurance as we are only twiddling a few bits. If the time were to increment by exactly one second and the process id were to increment by exactly one, in certain circumstances you would end up with identical seeds.
If you need truly distinct random number seeds, then you want to read 4 bytes from /dev/random and then use that as an integer to seed your RNG.
And again, PLEASE do not use this random number sequence for anything "important". And by important I mean anything more than a simple monte-carlo simulation or a game of rock-paper-scissors.
Problem
So normally I use something like: ``` srand(time(0)); ``` To get pseudo-randomness that changes with every program invocation. However, I'm now in a situation where I have a batch of programs that will all be starting at the same time and since `time` only changes every second, most of the time all of my programs start with the same seed. What is a better strategy for seeding my RNG when I want a bunch of programs to start at once and all get different seeds?