tmpnam.c 664 B

12345678910111213141516171819202122232425262728293031
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <unistd.h>
  5. #include <time.h>
  6. #include "libc.h"
  7. #include "syscall.h"
  8. #include "atomic.h"
  9. #define MAXTRIES 100
  10. char *tmpnam(char *s)
  11. {
  12. static int index;
  13. static char s2[L_tmpnam];
  14. struct timespec ts;
  15. int try = 0;
  16. unsigned n;
  17. if (!s) s = s2;
  18. if (__syscall(SYS_access, P_tmpdir, R_OK|W_OK|X_OK) != 0)
  19. return NULL;
  20. do {
  21. __syscall(SYS_clock_gettime, CLOCK_REALTIME, &ts, 0);
  22. n = ts.tv_nsec ^ (uintptr_t)&s ^ (uintptr_t)s;
  23. snprintf(s, L_tmpnam, "/tmp/t%x-%x", a_fetch_add(&index, 1), n);
  24. } while (!__syscall(SYS_access, s, F_OK) && try++<MAXTRIES);
  25. return try>=MAXTRIES ? 0 : s;
  26. }