2 * UCW Library -- Temporary Fastbufs
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/fastbuf.h"
14 #include "ucw/threads.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 (ctx->thread_id == 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, ctx->thread_id, cnt);
71 ASSERT(len < TEMP_FILE_NAME_LEN);
75 bopen_tmp_file(struct fb_params *params)
77 char name[TEMP_FILE_NAME_LEN];
78 int fd = open_tmp(name, O_RDWR | O_CREAT | O_TRUNC, 0600);
79 struct fastbuf *fb = bopen_fd_name(fd, params, name);
80 bconfig(fb, BCONFIG_IS_TEMP_FILE, 1);
85 open_tmp(char *name_buf, int open_flags, int mode)
87 int create_flags, fd, retry = 10;
90 temp_file_name(name_buf, &create_flags);
91 fd = ucw_open(name_buf, open_flags | create_flags, mode);
93 while (fd < 0 && errno == EEXIST && retry --);
95 die("Unable to create temp file %s: %m", name_buf);
100 bopen_tmp(uns buflen)
102 return bopen_tmp_file(&(struct fb_params){ .type = FB_STD, .buffer_size = buflen });
105 void bfix_tmp_file(struct fastbuf *fb, const char *name)
107 int was_temp = bconfig(fb, BCONFIG_IS_TEMP_FILE, 0);
108 ASSERT(was_temp == 1);
109 if (rename(fb->name, name))
110 die("Cannot rename %s to %s: %m", fb->name, name);
116 #include "ucw/getopt.h"
118 int main(int argc, char **argv)
121 if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
122 die("Hey, whaddya want?");
124 struct fastbuf *f = bopen_tmp(65536);
125 bputsn(f, "Hello, world!");