]> mj.ucw.cz Git - libucw.git/blob - ucw/fb-temp.c
The big move. Step #1: Move whole lib/ to ucw/.
[libucw.git] / ucw / fb-temp.c
1 /*
2  *      UCW Library -- Temporary Fastbufs
3  *
4  *      (c) 2002--2007 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "ucw/lib.h"
11 #include "ucw/conf.h"
12 #include "ucw/fastbuf.h"
13 #include "ucw/threads.h"
14
15 #include <stdio.h>
16 #include <unistd.h>
17 #include <sys/fcntl.h>
18
19 static char *temp_prefix = "/tmp/temp";
20
21 static struct cf_section temp_config = {
22   CF_ITEMS {
23     CF_STRING("Prefix", &temp_prefix),
24     CF_END
25   }
26 };
27
28 static void CONSTRUCTOR temp_global_init(void)
29 {
30   cf_declare_section("Tempfiles", &temp_config, 0);
31 }
32
33 void
34 temp_file_name(char *buf)
35 {
36   struct ucwlib_context *ctx = ucwlib_thread_context();
37   int cnt = ++ctx->temp_counter;
38   int pid = getpid();
39   if (ctx->thread_id == pid)
40     sprintf(buf, "%s%d-%d", temp_prefix, pid, cnt);
41   else
42     sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, ctx->thread_id, cnt);
43 }
44
45 struct fastbuf *
46 bopen_tmp_file(struct fb_params *params)
47 {
48   char name[TEMP_FILE_NAME_LEN];
49   temp_file_name(name);
50   struct fastbuf *fb = bopen_file(name, O_RDWR | O_CREAT | O_TRUNC, params);
51   bconfig(fb, BCONFIG_IS_TEMP_FILE, 1);
52   return fb;
53 }
54
55 struct fastbuf *
56 bopen_tmp(uns buflen)
57 {
58   return bopen_tmp_file(&(struct fb_params){ .type = FB_STD, .buffer_size = buflen });
59 }
60
61 void bfix_tmp_file(struct fastbuf *fb, const char *name)
62 {
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);
67   bclose(fb);
68 }
69
70 #ifdef TEST
71
72 #include "ucw/getopt.h"
73
74 int main(int argc, char **argv)
75 {
76   log_init(NULL);
77   if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
78     die("Hey, whaddya want?");
79
80   struct fastbuf *f = bopen_tmp(65536);
81   bputsn(f, "Hello, world!");
82   bclose(f);
83   return 0;
84 }
85
86 #endif