getrandom syscall in C not found

getrandom and getentropy were added to glibc in version 2.25. As of July 2017, most Linux distributions have not yet updated to this version (e.g. Debian’s most recent release, which just came out, has 2.24) but they should soon.

Here is how to use the glibc wrappers if available and fall back to the raw system call if not:

#define _GNU_SOURCE 1
#include <sys/types.h>
#include <unistd.h>

#if defined __GLIBC__ && defined __linux__

# if __GLIBC__ > 2 || __GLIBC_MINOR__ > 24
#  include <sys/random.h>

int
my_getentropy(void *buf, size_t buflen)
{
    return getentropy(buf, buflen);
}

# else /* older glibc */
#  include <sys/syscall.h>
#  include <errno.h>

int
my_getentropy(void *buf, size_t buflen)
{
    if (buflen > 256) {
        errno = EIO;
        return -1;
    }
    return syscall(SYS_getrandom, buf, buflen, 0);
}

# endif

#else /* not linux or not glibc */
#error "Need implementation for whatever operating system this is"

#endif

(As pointed out in other answers, it is also necessary to ensure you have kernel 3.17 or newer. Both the above versions of my_getentropy will fail and set errno to ENOSYS if run on an older kernel.)

Leave a Comment