Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
/* times are in mikroseconds */
/* #define USLEEPTIME 5000 */
#define LOOPTIME 10000
void usage(const char *progname) {
fprintf(stderr, "%s: usage\n"
"%s <tempfile>", progname, progname);
}
int main(int argc, char *argv[]) {
const char *tempfile;
struct timespec nano;
struct stat statbuf;
char buf[80];
char filename[PATH_MAX + 100];
int fd;
int rc;
int cnt = 0;
if (argc < 2) {
usage(argv[0]);
exit(1);
}
tempfile = argv[1];
sprintf(filename, "%s.%d.%d.XXXXXX", tempfile, getpid(), cnt++);
printf("using %s as temporary file\n", filename);
sprintf(buf, "%ld\n", getpid());
for ( ; ; usleep(LOOPTIME) ) {
/* check for existing tempfile ... */
if (stat(filename, &statbuf) == 0 || lstat(filename, &statbuf) == 0) {
sprintf(filename, "%s.%d.%d", tempfile, getpid(), cnt++);
printf("\ntempfile exists already - retrying with %s\n", filename);
continue;
}
usleep(LOOPTIME);
/* fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0600); */
memset(filename, '\0',PATH_MAX+100);
sprintf(filename, "%s.%d.%d.XXXXXX", tempfile, getpid(), cnt++);
printf("using %s as temporary file\n", filename);
fd = mkstemp(filename);
if (fd == -1) {
perror("open");
exit(2);
}
printf("The REAL temporary filename is: >%s<\n", filename);
rc = write(fd, buf, strlen(buf));
if (rc == -1) {
perror("write");
exit(2);
}
close(fd);
unlink(filename);
printf(".");
fflush(stdout);
}
return 0;
}