summaryrefslogtreecommitdiff
path: root/regress/sys/kern/kqueue/kqueue-random.c
blob: fb5fd00f808c3720bb3a4c7818c9ea2e87008f26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*	$OpenBSD: kqueue-random.c,v 1.12 2021/12/13 16:56:49 deraadt Exp $	*/
/*	Written by Michael Shalayeff, 2002, Public Domain	*/

#include <sys/types.h>
#include <sys/event.h>

#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "main.h"

#define MINIMUM(a, b)    (((a) < (b)) ? (a) : (b))

int
do_random(void)
{
	int n, fd, kq;
	struct timespec ts;
	struct kevent ev;
	u_int32_t buf[BUFSIZ];

	ASS((fd = open("/dev/random", O_RDONLY)) >= 0,
	    warn("open: /dev/random"));
	ASS(fcntl(fd, F_SETFL, O_NONBLOCK) == 0,
	    warn("fcntl"));

	ASS((kq = kqueue()) >= 0,
	    warn("kqueue"));

	memset(&ev, 0, sizeof(ev));
	ev.ident = fd;
	ev.filter = EVFILT_READ;
	ev.flags = EV_ADD | EV_ENABLE;
	n = kevent(kq, &ev, 1, NULL, 0, NULL);
	ASSX(n != -1);

	ts.tv_sec = 0;
	ts.tv_nsec = 0;
	n = kevent(kq, NULL, 0, &ev, 1, &ts);
	ASSX(n >= 0);

	n = MINIMUM((ev.data + 7) / 8, sizeof(buf));
	ASSX(read(fd, buf, n) > 0);

	close(kq);
	close(fd);

	return (0);
}