aboutsummaryrefslogtreecommitdiff
path: root/src/lib9/truerand.c
blob: aaf10f0a95020d62d8386d9ae5381d619bfdf93d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <u.h>
#include <libc.h>

ulong
truerand(void)
{
	int i, n;
	uchar buf[sizeof(ulong)];
	static int randfd = -1;

	if(randfd < 0){
		randfd = open("/dev/random", OREAD);
		fcntl(randfd, F_SETFD, FD_CLOEXEC);
	}
	if(randfd < 0)
		sysfatal("can't open /dev/random: %r");
	for(i=0; i<sizeof(buf); i += n)
		if((n = readn(randfd, buf+i, sizeof(buf)-i)) < 0)
			sysfatal("can't read /dev/random: %r");
	return *((ulong*)buf);
}