truerand.c 662 B

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