yuan
yuan

Reputation: 2534

file io with /dev/random takes too long

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

Upvotes: 5

Views: 1083

Answers (1)

Brian Cain
Brian Cain

Reputation: 14619

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.

Upvotes: 7

Related Questions