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
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.
On modern Linux systems, the in-kernel random number generator in /dev/random is considered cryptographically secure and, crucially, no longer blocks.
In Unix-like operating systems, /dev/random, /dev/urandom and /dev/arandom are special files that serve as pseudorandom number generators.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With