2 * UCW Library -- Temporary Files
4 * (c) 2002--2008 Martin Mares <mj@ucw.cz>
5 * (c) 2008 Michal Vaner <vorner@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
13 #include <ucw/threads.h>
15 #include <ucw/fastbuf.h>
19 #include <sys/fcntl.h>
24 static char *temp_prefix = "temp";
25 static char *temp_dir;
26 static int public_dir = 1;
28 static struct cf_section temp_config = {
30 CF_STRING("Dir", &temp_dir),
31 CF_STRING("Prefix", &temp_prefix),
32 CF_INT("PublicDir", &public_dir),
37 static void CONSTRUCTOR temp_global_init(void)
39 cf_declare_section("Tempfiles", &temp_config, 0);
43 temp_file_name(char *name_buf, int *open_flags)
46 if (!dir && !(dir = getenv("TMPDIR")))
53 if (gettimeofday(&tv, NULL))
54 die("gettimeofday() failed: %m");
55 len = snprintf(name_buf, TEMP_FILE_NAME_LEN, "%s/%s%u", dir, temp_prefix, (uns) tv.tv_usec);
61 struct ucwlib_context *ctx = ucwlib_thread_context();
62 int cnt = ++ctx->temp_counter;
64 if (ucwlib_thread_id(ctx) == pid)
65 len = snprintf(name_buf, TEMP_FILE_NAME_LEN, "%s/%s%d-%d", dir, temp_prefix, pid, cnt);
67 len = snprintf(name_buf, TEMP_FILE_NAME_LEN, "%s/%s%d-%d-%d", dir, temp_prefix, pid, ucwlib_thread_id(ctx), cnt);
71 ASSERT(len < TEMP_FILE_NAME_LEN);
75 open_tmp(char *name_buf, int open_flags, int mode)
77 int create_flags, fd, retry = 10;
80 temp_file_name(name_buf, &create_flags);
81 fd = ucw_open(name_buf, open_flags | create_flags, mode);
83 while (fd < 0 && errno == EEXIST && retry --);
85 die("Unable to create temp file %s: %m", name_buf);
91 #include <ucw/getopt.h>
93 int main(int argc, char **argv)
96 if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
97 die("Hey, whaddya want?");
99 char buf[TEMP_FILE_NAME_LEN];
100 int fd = open_tmp(buf, O_RDWR | O_CREAT | O_TRUNC, 0666);