tempnam.c 794 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <time.h>
  6. #include "libc.h"
  7. #include "atomic.h"
  8. #define MAXTRIES 100
  9. char *tempnam(const char *dir, const char *pfx)
  10. {
  11. static int index;
  12. char *s;
  13. struct timespec ts;
  14. int pid = getpid();
  15. size_t l;
  16. int n;
  17. int try=0;
  18. if (!dir) dir = P_tmpdir;
  19. if (!pfx) pfx = "temp";
  20. if (access(dir, R_OK|W_OK|X_OK) != 0)
  21. return NULL;
  22. l = strlen(dir) + 1 + strlen(pfx) + 3*(sizeof(int)*3+2) + 1;
  23. s = malloc(l);
  24. if (!s) return s;
  25. do {
  26. clock_gettime(CLOCK_REALTIME, &ts);
  27. n = ts.tv_nsec ^ (unsigned)&s ^ (unsigned)s;
  28. snprintf(s, l, "%s/%s-%d-%d-%x", dir, pfx, pid, a_fetch_add(&index, 1), n);
  29. } while (!access(s, F_OK) && try++<MAXTRIES);
  30. if (try>=MAXTRIES) {
  31. free(s);
  32. return 0;
  33. }
  34. return s;
  35. }