Is reading /dev/urandom thread-safe?

2019-03-27 02:52发布

问题:

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?

回答1:

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.