C: Fill an array of unsigned integers with random data using getrandom()
Often I need to generate random unsigned integers for seeding PRNGs. The best way is using the getrandom() system function to read OS level randomness into your array.
#include <sys/random.h>
#include <errno.h>
// Read from system random filling up an array of u64s
int fill_urandom_u64(uint64_t *buf, size_t count) {
size_t bytes = count * sizeof(uint64_t);
unsigned char *p = (unsigned char *)buf;
while (bytes > 0) {
ssize_t n = getrandom(p, bytes, 0);
if (n < 0) {
if (errno == EINTR) continue;
return -1;
}
p += n;
bytes -= n;
}
return 0;
}
Declare your array of integers, and the pass it as a pointer to this function to fill with random bytes from your OS. This will get you a bunch of random integers you can use for seeding PRNGs.
uint64_t seed[4];
fill_urandom_u64(seed, 4);
Tags:



