]> mj.ucw.cz Git - libucw.git/blob - lib/fb-temp.c
Creation of temporary files is now thread-safe (ugh).
[libucw.git] / lib / fb-temp.c
1 /*
2  *      UCW Library -- Temporary Fastbufs
3  *
4  *      (c) 2002--2006 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 "lib/lib.h"
11 #include "lib/conf.h"
12 #include "lib/fastbuf.h"
13 #include "lib/threads.h"
14
15 #include <unistd.h>
16 #include <sys/fcntl.h>
17
18 static byte *temp_prefix = "/tmp/temp";
19
20 static struct cf_section temp_config = {
21   CF_ITEMS {
22     CF_STRING("Prefix", &temp_prefix),
23     CF_END
24   }
25 };
26
27 static void CONSTRUCTOR temp_global_init(void)
28 {
29   cf_declare_section("Tempfiles", &temp_config, 0);
30 }
31
32 void
33 temp_file_name(byte *buf)
34 {
35   int cnt = ++ucwlib_thread_context()->temp_counter;
36   int pid = getpid();
37 #if 0
38   /* FIXME: This is Linux-specific and not declared anywhere :( */
39   int tid = gettid();
40 #else
41   int tid = pid;
42 #endif
43   if (pid == tid)
44     sprintf(buf, "%s%d-%d", temp_prefix, pid, cnt);
45   else
46     sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, tid, cnt);
47 }
48
49 struct fastbuf *
50 bopen_tmp(uns buflen)
51 {
52   byte buf[TEMP_FILE_NAME_LEN];
53   struct fastbuf *f;
54
55   temp_file_name(buf);
56   f = bopen(buf, O_RDWR | O_CREAT | O_TRUNC, buflen);
57   bconfig(f, BCONFIG_IS_TEMP_FILE, 1);
58   return f;
59 }
60
61 #ifdef TEST
62
63 #include "lib/getopt.h"
64
65 int main(int argc, char **argv)
66 {
67   log_init(NULL);
68   if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
69     die("Hey, whaddya want?");
70
71   struct fastbuf *f = bopen_tmp(65536);
72   bputsn(f, "Hello, world!");
73   bclose(f);
74   return 0;
75 }
76
77 #endif