This is the code:
unsigned int number;
FILE* urandom = fopen("/dev/urandom", "r");
if (urandom) {
size_t bytes_read = fread(&number, 1, sizeof(number), urandom);
DCHECK(bytes_read == sizeof(number));
fclose(urandom);
} else {
NOTREACHED();
}
If not, how do I make it thread-safe?
There is no difference between /dev/random and /dev/urandom; both behave identically. Apple's iOS also uses Yarrow.
On modern Linux systems, the in-kernel random number generator in /dev/random is considered cryptographically secure and, crucially, no longer blocks.
Because its purpose is not to block. That's literally what distinguishes it from /dev/random . So you don't have to worry about blocking, but the bits you get from it may not be quite as random as those from /dev/random .
write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.
As long as each execution of the function is in its own thread (i.e., the local variables number
, urandom
, bytes_read
are not shared between threads), I don't see any thread-safety problems. Each thread will then have its own file descriptor into /dev/urandom
. /dev/urandom
can be opened simultaneously from multiple processes, so that's okay.
By the way, /dev/urandom
can fail to open, and your code should deal with it. Some causes are: running out of available file descriptors; /dev
not properly mounted (although in this case you have bigger problems); your program is being run in a special chroot
which denies access to any devices; etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With