getentropy.c 610 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #define _BSD_SOURCE
  2. #include <unistd.h>
  3. #include <sys/random.h>
  4. #include <pthread.h>
  5. #include <errno.h>
  6. int getentropy(void *buffer, size_t len)
  7. {
  8. int cs, ret = 0;
  9. char *pos = buffer;
  10. if (len > 256) {
  11. errno = EIO;
  12. return -1;
  13. }
  14. #if defined(__linux__) && !defined(__ANDROID__)
  15. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
  16. #endif
  17. while (len) {
  18. ret = getrandom(pos, len, 0);
  19. if (ret < 0) {
  20. if (errno == EINTR) continue;
  21. else break;
  22. }
  23. pos += ret;
  24. len -= ret;
  25. ret = 0;
  26. }
  27. #if defined(__linux__) && !defined(__ANDROID__)
  28. pthread_setcancelstate(cs, 0);
  29. #endif
  30. return ret;
  31. }