]> mj.ucw.cz Git - libucw.git/blob - ucw/tempfile.c
UCW: Adapted to use ucw_thread_id()
[libucw.git] / ucw / tempfile.c
1 /*
2  *      UCW Library -- Temporary Files
3  *
4  *      (c) 2002--2008 Martin Mares <mj@ucw.cz>
5  *      (c) 2008 Michal Vaner <vorner@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "ucw/lib.h"
12 #include "ucw/conf.h"
13 #include "ucw/threads.h"
14 #include "ucw/lfs.h"
15 #include "ucw/fastbuf.h"
16
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <sys/fcntl.h>
20 #include <stdlib.h>
21 #include <sys/time.h>
22 #include <errno.h>
23
24 static char *temp_prefix = "temp";
25 static char *temp_dir;
26 static int public_dir = 1;
27
28 static struct cf_section temp_config = {
29   CF_ITEMS {
30     CF_STRING("Dir", &temp_dir),
31     CF_STRING("Prefix", &temp_prefix),
32     CF_INT("PublicDir", &public_dir),
33     CF_END
34   }
35 };
36
37 static void CONSTRUCTOR temp_global_init(void)
38 {
39   cf_declare_section("Tempfiles", &temp_config, 0);
40 }
41
42 void
43 temp_file_name(char *name_buf, int *open_flags)
44 {
45   char *dir = temp_dir;
46   if (!dir && !(dir = getenv("TMPDIR")))
47     dir = "/tmp";
48
49   int len;
50   if (public_dir)
51     {
52       struct timeval tv;
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);
56       if (open_flags)
57         *open_flags = O_EXCL;
58     }
59   else
60     {
61       struct ucwlib_context *ctx = ucwlib_thread_context();
62       int cnt = ++ctx->temp_counter;
63       int pid = getpid();
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);
66       else
67         len = snprintf(name_buf, TEMP_FILE_NAME_LEN, "%s/%s%d-%d-%d", dir, temp_prefix, pid, ucwlib_thread_id(ctx), cnt);
68       if (open_flags)
69         *open_flags = 0;
70     }
71   ASSERT(len < TEMP_FILE_NAME_LEN);
72 }
73
74 int
75 open_tmp(char *name_buf, int open_flags, int mode)
76 {
77   int create_flags, fd, retry = 10;
78   do
79     {
80       temp_file_name(name_buf, &create_flags);
81       fd = ucw_open(name_buf, open_flags | create_flags, mode);
82     }
83   while (fd < 0 && errno == EEXIST && retry --);
84   if (fd < 0)
85     die("Unable to create temp file %s: %m", name_buf);
86   return fd;
87 }
88
89 #ifdef TEST
90
91 #include "ucw/getopt.h"
92
93 int main(int argc, char **argv)
94 {
95   log_init(NULL);
96   if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
97     die("Hey, whaddya want?");
98
99   char buf[TEMP_FILE_NAME_LEN];
100   int fd = open_tmp(buf, O_RDWR | O_CREAT | O_TRUNC, 0666);
101   close(fd);
102   unlink(buf);
103   return 0;
104 }
105
106 #endif