2011-02-12 00:22:29 -05:00
|
|
|
#include <stdio.h>
|
2014-05-27 00:44:23 -04:00
|
|
|
#include <fcntl.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <limits.h>
|
2011-02-12 00:22:29 -05:00
|
|
|
#include <string.h>
|
2014-05-27 00:44:23 -04:00
|
|
|
#include "syscall.h"
|
2011-03-29 09:00:22 -04:00
|
|
|
|
|
|
|
#define MAXTRIES 100
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2014-05-27 00:44:23 -04:00
|
|
|
char *__randname(char *);
|
|
|
|
|
2011-02-12 00:22:29 -05:00
|
|
|
char *tempnam(const char *dir, const char *pfx)
|
|
|
|
{
|
2014-05-27 00:44:23 -04:00
|
|
|
char s[PATH_MAX];
|
|
|
|
size_t l, dl, pl;
|
|
|
|
int try;
|
|
|
|
int r;
|
2011-02-12 00:22:29 -05:00
|
|
|
|
|
|
|
if (!dir) dir = P_tmpdir;
|
|
|
|
if (!pfx) pfx = "temp";
|
|
|
|
|
2014-05-27 00:44:23 -04:00
|
|
|
dl = strlen(dir);
|
|
|
|
pl = strlen(pfx);
|
|
|
|
l = dl + 1 + pl + 1 + 6;
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2014-05-27 00:44:23 -04:00
|
|
|
if (l >= PATH_MAX) {
|
|
|
|
errno = ENAMETOOLONG;
|
2011-03-29 09:00:22 -04:00
|
|
|
return 0;
|
2011-02-12 00:22:29 -05:00
|
|
|
}
|
2014-05-27 00:44:23 -04:00
|
|
|
|
|
|
|
memcpy(s, dir, dl);
|
|
|
|
s[dl] = '/';
|
|
|
|
memcpy(s+dl+1, pfx, pl);
|
|
|
|
s[dl+1+pl] = '_';
|
|
|
|
|
|
|
|
for (try=0; try<MAXTRIES; try++) {
|
|
|
|
__randname(s+l-6);
|
2014-05-29 21:01:32 -04:00
|
|
|
#ifdef SYS_lstat
|
2014-05-27 00:44:23 -04:00
|
|
|
r = __syscall(SYS_lstat, s, &(struct stat){0});
|
2014-05-29 21:01:32 -04:00
|
|
|
#else
|
|
|
|
r = __syscall(SYS_fstatat, AT_FDCWD, s,
|
|
|
|
&(struct stat){0}, AT_SYMLINK_NOFOLLOW);
|
|
|
|
#endif
|
2014-05-27 00:44:23 -04:00
|
|
|
if (r == -ENOENT) return strdup(s);
|
|
|
|
}
|
|
|
|
return 0;
|
2011-02-12 00:22:29 -05:00
|
|
|
}
|