foo.cpp

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3100/spring2026/notes/flags/code/foo.cpp
 
#include <stdio.h>
#include <sys/random.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main() {
    unsigned int num;
    ssize_t result;
    size_t size = sizeof(unsigned int);
    unsigned int flags = 0; // Use default behavior (read from urandom source, potentially blocking on initial seed)

    // Call the getrandom system call
    for(int i =0; i < 10; ++i) {
    result = getrandom(&num, size, flags);

    if (result == -1) {
        // Check errno for specific errors
        if (errno == EAGAIN) {
            fprintf(stderr, "Error: not enough entropy to fulfill request without blocking. Try using GRND_NONBLOCK flag if this is a startup issue.\n");
        } else {
            fprintf(stderr, "Error calling getrandom: %s\n", strerror(errno));
        }
        return 1;
    } else if (result < size) {
        // Should not happen for small requests from urandom source, but good practice to check
        fprintf(stderr, "Warning: only obtained %zd bytes, requested %zd\n", result, size);
    } else {
        printf("Successfully generated random number: %u\n", num);
    }
    }

    return 0;
}