Go to main content

man pages section 2: System Calls

Exit Print View

Updated: Wednesday, July 27, 2022



getrandom, getentropy - retrieve data from the kernel random pool


#include <sys/random.h>

ssize_t getrandom(void *buf, size_t buflen, unsigned int flags);

#include <unistd.h>
int getentropy(void *buf, size_t buflen);


The getrandom() function can be used to request buflen bytes of data from the kernel random pool, which is to be placed into the buffer, pointed to by buf. It is recommended to use the getrandom() function instead of open(2) and read(2) functions on the /dev/random or /dev/urandom device.

The random data returned by the getrandom() function is processed by a FIPS 140-2 approved deterministic random bit generator (DRBG).

If the GRND_RANDOM flag is set, then the implementation uses the same pool as /dev/random, otherwise the /dev/urandom pool is used.

If no entropy is available in the pool, the getrandom() function will block unless the GRND_NONBLOCK flag is set. In this case, the function returns -1 and errno is set to EAGAIN. Note that the number of bytes returned can be less than requested or 0. Callers need to check the return value to determine if random bytes were returned. This means this is not an acceptable calling sequence:

(void) getrandom(&buf, sizeof (buf), 0);

The getentropy() function is always a blocking call, it is expected to be used only to seed a userspace implementation of a random bit generator.

Return Values

Upon successful completion, the getrandom() function returns the number of bytes written to buf. Otherwise, it returns 0 and sets errno to indicate the error.

Upon successful completion, the getentropy() function returns 0. Otherwise, it returns -1 and sets errno to indicate the error.


The getrandom() and getentropy() functions fail if:


Invalid flags or flag combinations

  • bufsz is <= 0 or > 1040, when GRND_RANDOM is set

  • bufsz is <= 0 or > 133120, when GRND_RANDOM is not set


buf is an invalid address.


No entropy is available and GRND_NONBLOCK is set.

The getentropy() call also fails if:


More than 256 bytes are requested, or the returned amount of entropy does not match the request.


Example 1 Using the getrandom() function
#include <sys/random.h>
#include <stdlib.h>
size_t bufsz = 1024;
char *buf;
int ret;
buf = malloc(bufsz);
ret = getrandom(buf, bufsz, GRND_RANDOM);
if (ret != bufsz) {
        perror("getrandom failed");
Example 2 Using the getentropy() function
#include <sys/random.h>
#include <stdlib.h>
size_t entsz = 128;
char *entropy;
int err;
entropy = malloc(entsz);
err = getentropy(entropy, entsz);
if (err != 0) {
        perror("getentropy failed");
/* Use entropy to seed our RNG */


See attributes(7) for descriptions of the following attributes:

Interface Stability

See Also