]> code.delx.au - linux-getrandom-userspace/blob - getrandom.c
Metadata
[linux-getrandom-userspace] / getrandom.c
1 #include <fcntl.h>
2 #include <unistd.h>
3 #include <sys/random.h>
4
5 ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) {
6 char* filename = flags & GRND_RANDOM ? "/dev/random" : "/dev/urandom";
7 int nonblock = flags & GRND_NONBLOCK ? O_NONBLOCK : 0;
8 int oflags = O_CLOEXEC | nonblock;
9
10 int fd = open(filename, oflags);
11 if (fd < 0) {
12 return -1;
13 }
14
15 ssize_t bytes = read(fd, buf, buflen);
16
17 close(fd);
18
19 return bytes;
20 }