2011-02-12 00:22:29 -05:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <stdlib.h>
|
2011-06-13 20:52:01 -04:00
|
|
|
#include <stdint.h>
|
2011-02-12 00:22:29 -05:00
|
|
|
#include <unistd.h>
|
2011-03-29 09:00:22 -04:00
|
|
|
#include <time.h>
|
2011-02-12 00:22:29 -05:00
|
|
|
#include "libc.h"
|
2011-03-29 09:00:22 -04:00
|
|
|
#include "atomic.h"
|
|
|
|
|
|
|
|
#define MAXTRIES 100
|
2011-02-12 00:22:29 -05:00
|
|
|
|
|
|
|
char *tempnam(const char *dir, const char *pfx)
|
|
|
|
{
|
|
|
|
static int index;
|
|
|
|
char *s;
|
2011-03-29 09:00:22 -04:00
|
|
|
struct timespec ts;
|
2011-02-12 00:22:29 -05:00
|
|
|
int pid = getpid();
|
2011-03-29 09:00:22 -04:00
|
|
|
size_t l;
|
|
|
|
int n;
|
|
|
|
int try=0;
|
2011-02-12 00:22:29 -05:00
|
|
|
|
|
|
|
if (!dir) dir = P_tmpdir;
|
|
|
|
if (!pfx) pfx = "temp";
|
|
|
|
|
|
|
|
if (access(dir, R_OK|W_OK|X_OK) != 0)
|
|
|
|
return NULL;
|
|
|
|
|
2011-03-29 09:00:22 -04:00
|
|
|
l = strlen(dir) + 1 + strlen(pfx) + 3*(sizeof(int)*3+2) + 1;
|
2011-02-12 00:22:29 -05:00
|
|
|
s = malloc(l);
|
2011-03-29 09:00:22 -04:00
|
|
|
if (!s) return s;
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2011-03-29 09:00:22 -04:00
|
|
|
do {
|
|
|
|
clock_gettime(CLOCK_REALTIME, &ts);
|
2011-06-13 20:52:01 -04:00
|
|
|
n = ts.tv_nsec ^ (uintptr_t)&s ^ (uintptr_t)s;
|
2011-03-29 09:00:22 -04:00
|
|
|
snprintf(s, l, "%s/%s-%d-%d-%x", dir, pfx, pid, a_fetch_add(&index, 1), n);
|
|
|
|
} while (!access(s, F_OK) && try++<MAXTRIES);
|
|
|
|
if (try>=MAXTRIES) {
|
|
|
|
free(s);
|
|
|
|
return 0;
|
2011-02-12 00:22:29 -05:00
|
|
|
}
|
2011-03-29 09:00:22 -04:00
|
|
|
return s;
|
2011-02-12 00:22:29 -05:00
|
|
|
}
|