getrandom(2)

getrandom2

Get random data

Usage

#include <sys/random.h>

ssize_t

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

Library

Standard C Library (libc, -lc)

Overview

getrandom() fills buf with up to buflen bytes of random data.

The flags argument may include zero or more of the following:

‘GRND_NONBLOCK’

Return EAGAIN instead of blocking, if the random(4) device has not yet been seeded. By default, getrandom() will block until the device is seeded.

‘GRND_RANDOM’

This flag does nothing on FreeBSD. /dev/random and /dev/urandom are identical.

‘GRND_INSECURE’

This flag is treated as an alternative name for GRND_NONBLOCK. It is provided solely for API compatibility with Linux.

If the random(4) device has been seeded, reads of up to 256 bytes will always return as many bytes as requested and will not be interrupted by signals.

Return values

Upon successful completion, the number of bytes which were actually read is returned. For requests larger than 256 bytes, this can be fewer bytes than were requested. Otherwise, -1 is returned and the global variable errno is set to indicate the error.

Errors

The getrandom() operation returns the following errors:

[EAGAIN]

The ‘GRND_NONBLOCK’ (or ‘GRND_INSECURE’) flag was set and the random(4) device was not yet seeded.

[EFAULT]

The buf parameter points to an invalid address.

[EINTR]

The sleep was interrupted by a signal.

[EINVAL]

An invalid flags was specified.

[EINVAL]

The requested buflen was larger than IOSIZE_MAX.

Caveats

Unlike Linux, the GRND_INSECURE flag on FreeBSD does not produce any output before the random(4) device is seeded.

Releases

20 releases since FreeBSD 12.0-RELEASE; the text changed 6 times.

  1. 12.0
  2. 12.1
  3. 12.2
  4. 12.3
  5. 12.4
  6. 13.0–13.2
  7. 13.3–16.0

Standards

getrandom() is non-standard. It is present in Linux.

History

The getrandom() system call first appeared in FreeBSD 12.0.

From base 16.0-CURRENT-20261027-61c70dc16a79 in FreeBSD 16.0-CURRENT (2026-10-27). Parsed by carta from the page's mdoc source.