fix tempnam name generation, and a small bug in tmpnam on retry limit
[musl] / src / stdio / tempnam.c
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
9 #define MAXTRIES 100
10
11 char *tempnam(const char *dir, const char *pfx)
12 {
13         static int index;
14         char *s;
15         struct timespec ts;
16         int pid = getpid();
17         size_t l;
18         int n;
19         int try=0;
20
21         if (!dir) dir = P_tmpdir;
22         if (!pfx) pfx = "temp";
23
24         if (access(dir, R_OK|W_OK|X_OK) != 0)
25                 return NULL;
26
27         l = strlen(dir) + 1 + strlen(pfx) + 3*(sizeof(int)*3+2) + 1;
28         s = malloc(l);
29         if (!s) return s;
30
31         do {
32                 clock_gettime(CLOCK_REALTIME, &ts);
33                 n = ts.tv_nsec ^ (unsigned)&s ^ (unsigned)s;
34                 snprintf(s, l, "%s/%s-%d-%d-%x", dir, pfx, pid, a_fetch_add(&index, 1), n);
35         } while (!access(s, F_OK) && try++<MAXTRIES);
36         if (try>=MAXTRIES) {
37                 free(s);
38                 return 0;
39         }
40         return s;
41 }