2 * UCW Library -- Temporary Fastbufs
4 * (c) 2002--2007 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
12 #include "lib/fastbuf.h"
13 #include "lib/threads.h"
17 #include <sys/fcntl.h>
19 static char *temp_prefix = "/tmp/temp";
21 static struct cf_section temp_config = {
23 CF_STRING("Prefix", &temp_prefix),
28 static void CONSTRUCTOR temp_global_init(void)
30 cf_declare_section("Tempfiles", &temp_config, 0);
34 temp_file_name(char *buf)
36 struct ucwlib_context *ctx = ucwlib_thread_context();
37 int cnt = ++ctx->temp_counter;
39 if (ctx->thread_id == pid)
40 sprintf(buf, "%s%d-%d", temp_prefix, pid, cnt);
42 sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, ctx->thread_id, cnt);
46 bopen_tmp_file(struct fb_params *params)
48 char name[TEMP_FILE_NAME_LEN];
50 struct fastbuf *fb = bopen_file(name, O_RDWR | O_CREAT | O_TRUNC, params);
51 bconfig(fb, BCONFIG_IS_TEMP_FILE, 1);
58 return bopen_tmp_file(&(struct fb_params){ .type = FB_STD, .buffer_size = buflen });
61 void bfix_tmp_file(struct fastbuf *fb, const char *name)
63 int was_temp = bconfig(fb, BCONFIG_IS_TEMP_FILE, 0);
64 ASSERT(was_temp == 1);
65 if (rename(fb->name, name))
66 die("Cannot rename %s to %s: %m", fb->name, name);
72 #include "lib/getopt.h"
74 int main(int argc, char **argv)
77 if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
78 die("Hey, whaddya want?");
80 struct fastbuf *f = bopen_tmp(65536);
81 bputsn(f, "Hello, world!");