I have a program that I made that picks a random number for a port to receive a UDP packet on. The program seeds the rand function using some data from /dev/random. I loop through getting data 4 times to get a sufficient amount of data for srand.
This is the code that I use to generate the data for srand.
FILE *random_file = fopen("/dev/random","r");
std::string random_seed_str;
for(int i = 0; i < 3; i ) {
int seed_element = getc(random_file);
std::string element_string = std::to_string(seed_element);
random_seed_str = element_string;
}
int random_seed = stoi(random_seed_str);
srand( random_seed );
Now this works fine if I am running my program from the commandline one at a time. But when I start to use it in the application we designed it for, the program starts to randomly freeze at this line:
int seed_element = getc(random_file);
The application running it runs the program at random intervals and run's the programs in parallel (Upto 12 instances at a time).
The only thing I can think it causing it is if two instances of the same program try to access /dev/random via getc at the same time and it stalls.
I can't use seconds to act as my seed as, because it is running many instances of the program at the same time, I have had many programs collide by generating the same random numbers.
Is there any better way to get randomness?
CodePudding user response:
You should use the <random>
module of the standard library:
#include <random> //import random module
std::random_device rd; //use a random device to seed
std::default_random_engine re; //use a random engine to generate random bytes
re.seed(rd()); //seed the random engine
re(); //now use the random bytes, you can also instantiate a distribution to have values following a specific distribution.
CodePudding user response:
Using c random's header. Also add a distribution that controls how numbers are distributes (eg. normal, standard etc.).
#include <random>
// get 'entropy' from device that generates random numbers itself
// to seed a mersenne twister (pseudo) random generator
std::mt19937 generator(std::random_device{}());
// setup a distribution from 0 to 10
// in this case equal chance for all numbers.
std::uniform_int_distribution<int> distribution(0,10);
int main()
{
// generate a random value between 0 and 10
int value = distribution(generator);
return value;
}