9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

truerand.c (662B)


      1 #include <u.h>
      2 #include <libc.h>
      3 
      4 ulong
      5 truerand(void)
      6 {
      7 	int i, n;
      8 	uchar buf[sizeof(ulong)];
      9 	ulong x;
     10 	static int randfd = -1;
     11 	static char *randfile;
     12 
     13 	if(randfd < 0){
     14 		randfd = open(randfile="/dev/random", OREAD);
     15 		/* OpenBSD lets you open /dev/random but not read it! */
     16 		if(randfd < 0 || read(randfd, buf, 1) != 1)
     17 			randfd = open(randfile="/dev/srandom", OREAD);	/* OpenBSD */
     18 		if(randfd < 0)
     19 			sysfatal("can't open %s: %r", randfile);
     20 		fcntl(randfd, F_SETFD, FD_CLOEXEC);
     21 	}
     22 	for(i=0; i<sizeof(buf); i += n)
     23 		if((n = readn(randfd, buf+i, sizeof(buf)-i)) < 0)
     24 			sysfatal("can't read %s: %r", randfile);
     25 	memmove(&x, buf, sizeof x);
     26 	return x;
     27 }