How to generate a good random seed to pass to srand()?
I am writing a C++ program which needs to create a temporary file for its internal usage. I would like to allow concurrent executions of the program by running multiple processes, so the temporary file name needs to be randomized, that way each spawned process will generate a unique temporary file name for its own use.
I am using rand() to generate random characters for 开发者_运维知识库part of the file name, so i need to initialize the random number generator's seed using srand().
What options are there for passing a good argument to srand() such that two processes will not be initialized with the same seed value? My code needs to work both on Windows and on Linux.
The question is actually asking how to create a uniquely-named temporary file.
The operating system probably provides an API for this, which means you do not have to generate your own name.
On Windows, its called GetTempFileName()
and GetTempPath()
.
On Unix, use tmpfile()
.
(Windows supports tmpfile()
too; however, I've heard reports that from others that, whilst it works nicely on XP, it fails on Vista if you're on the C: drive and you are not an administrator; best to use the GetTempFileName()
method with a custom, safe path)
If you are trully just needing a temp file you can use:
FILE* tmpfile(); // Generate an unnamed temporary file.
char* tmpnam(char* s); // Generate a file name in the director specified by TMPDIR
Use time:
srand(time(NULL));
Also note that rand() probably is not thread safe.
So be careful how you use it. Two threads entering rand at the same time are going to cause problems.
I've never used it myself, but you might be able to use tmpnam()
to generate your temporary file name. A quick search indicated support on both Windows and Linux.
you could get the time in microseconds, and multiply it by a large number to get a seed. However, collisions can always happen, no matter what seed.
On unix systems, read a value out of /dev/random
Different processes will have different process IDs. However, adding that straight to the time would be a bit careless, as it's often a small number. It's not a big problem though: the underlying problem is that both the time and the process ID have their entropy concentrated in their lowest bits. By simply bit-reversing either and XOR'ing the result, you get good entropy in all bits.
I would suggest that you do not use a random file name, but instead create a unique file name from the process id and the current time (if the time resolution you can read is sufficient for you, which it should be). I don't know enough about your problem, but I suspect that there is no benefit from using a random name, and the risk for collisions may be very real. This is true even if you use the operating system to create the files for you which was suggested in another answer.
精彩评论