views:

1003

answers:

1

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?

+5  A: 

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.

Chris Jester-Young
Clearly it ought to be safe, for the sake of sanity, but I can't find anything in man 4 random that specifies that it is. For instance if urandom has fallen back to PRNG mode, could two simultaneous callers ever see the same output other than by chance? Surely not, but where do the docs say not?
Steve Jessop