Why doesn't getrandom () compile?

Silly question, I'm probably missing from the title, but the man page says that I just need to #include <linux/random.h>

.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <linux/random.h>

#define BITS 8192
#define BYTES (BITS >> 3)

int main() {
    uint8_t array[BYTES];

    printf("started...");
    int r = getrandom(array, BYTES, 0);
    if (r) exit(1);

    return 0;
}

      

Mistake:

chris@purple:~/lunch/bitarray$ make && ./bitarray 
clang -g -Wall -Wpedantic -Werror -std=c11 -O2 -save-temps bitarray.c -o bitarray
bitarray.c:13:10: error: implicit declaration of function 'getrandom' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
 int r = getrandom(array, (8192 >> 3), 0);
         ^
1 error generated.
Makefile:10: recipe for target 'bitarray' failed
make: *** [bitarray] Error 1

      

(Also crashing in gcc.)

chris@purple:~/lunch/bitarray$ cat /etc/lsb-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS"
chris@purple:~/lunch/bitarray$ uname -a
Linux purple 4.4.0-83-generic #106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

      

+3


source to share


1 answer


It looks like some Linux systems have a man page for getrandom

and correct syscall definitions, but not a C function. This gives you enough to create your own:

// _GNU_SOURCE should be set before *any* includes.
// Alternatively, pass to compiler with -D, or enable GNU extensions
// with -std=gnu11 (or omit -std completely)
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>

int my_getrandom(void *buf, size_t buflen, unsigned int flags)
{
    return (int)syscall(SYS_getrandom, buf, buflen, flags);
}

// remove this when we have a real getrandom():
#define getrandom  my_getrandom
// and replace it with
// #include <linux/random.h>

      



#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#define BITS 8192
#define BYTES (BITS >> 3)

int main() {
    uint8_t array[BYTES];

    printf("started...\n");
    int r = getrandom(array, sizeof array, 0);
    return r;
}

      

+4


source







All Articles