Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reading /dev/urandom thread-safe?

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?

like image 482
Paweł Hajdan Avatar asked Sep 25 '08 14:09

Paweł Hajdan


People also ask

What is the difference between Dev random and Dev Urandom?

There is no difference between /dev/random and /dev/urandom; both behave identically. Apple's iOS also uses Yarrow.

Is Dev random safe?

On modern Linux systems, the in-kernel random number generator in /dev/random is considered cryptographically secure and, crucially, no longer blocks.

Does Urandom block?

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 .

Is write function thread safe?

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.


1 Answers

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.

like image 145
Chris Jester-Young Avatar answered Oct 06 '22 19:10

Chris Jester-Young