Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file io with /dev/random takes too long

Tags:

c++

I want to write a program to generate really random number using /dev/random on linux, but later I find the running time of it is quite unacceptable occasionally. C version of it run fast consistently.

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc,char*argv[])
{
    ifstream random("/dev/random", ios_base::in);
    int t;
    random.read(reinterpret_cast<char*>(&t), sizeof(t));
    cout << t << endl;
    random.close();
    return 0;
}

The time statistic of running time

$: time ./random 
-1040810404

real    0m0.004s
user    0m0.000s
sys 0m0.000s

$: time ./random 
-1298913761

real    0m4.119s
user    0m0.000s
sys 0m0.000s
like image 221
yuan Avatar asked Jul 17 '13 04:07

yuan


People also ask

Why is Dev random so slow?

On most Linux systems, /dev/random is powered from actual entropy gathered by the environment. If your system isn't delivering a large amount of data from /dev/random , it likely means that you're not generating enough environmental randomness to power it.

Is Dev random blocking?

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

What is Dev random in Linux?

In Unix-like operating systems, /dev/random, /dev/urandom and /dev/arandom are special files that serve as pseudorandom number generators.


1 Answers

You have likely drained the entropy pool. Creating (ok harvesting) entropy is based on device drivers which sample qualities of the physical world which are mostly unpredictable. But if those devices are not very active or if the entropy-producing algorithm stalls, your reads from /dev/random will too.

Can you use /dev/urandom? If not, you should look into ways that you can produce more entropy in a more deterministic fashion.

Here are some suggestions from an article regarding a similar problem:

  • Involve an audio entropy daemon like AED to gather noise from your datacenter with an open microphone, maybe combine it with a webcam noise collector like VED. Other sources are talking about “Cryptographic Randomness from Air Turbulence in Disk devices“. :)
  • Use the Entropy Gathering Daemon to collect weaker entropy from randomness of userspace programs.
like image 101
Brian Cain Avatar answered Oct 20 '22 00:10

Brian Cain