]> mj.ucw.cz Git - libucw.git/blob - lib/fb-temp.c
ed7623ffc85edc5989678a5be0106c5124064881
[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
14 #include <unistd.h>
15 #include <sys/fcntl.h>
16
17 static byte *temp_prefix = "/tmp/temp";
18
19 static struct cf_section temp_config = {
20   CF_ITEMS {
21     CF_STRING("Prefix", &temp_prefix),
22     CF_END
23   }
24 };
25
26 static void CONSTRUCTOR temp_global_init(void)
27 {
28   cf_declare_section("Tempfiles", &temp_config, 0);
29 }
30
31 #ifdef CONFIG_UCW_THREADS
32 #include <pthread.h>
33
34 static pthread_key_t temp_counter_key;
35
36 static void CONSTRUCTOR
37 temp_key_init(void)
38 {
39   if (pthread_key_create(&temp_counter_key, NULL) < 0)
40     die("Cannot create fbdir_queue_key: %m");
41 }
42
43 void
44 temp_file_name(byte *buf)
45 {
46   int cnt = (int) pthread_getspecific(temp_counter_key);
47   cnt++;
48   pthread_setspecific(temp_counter_key, (void *) cnt);
49
50   int pid = getpid();
51 #if 0
52   /* FIXME: This is Linux-specific and not declared anywhere :( */
53   int tid = gettid();
54 #else
55   int tid = pid;
56 #endif
57   if (pid == tid)
58     sprintf(buf, "%s%d-%d", temp_prefix, pid, cnt);
59   else
60     sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, tid, cnt);
61 }
62
63 #else
64
65 void
66 temp_file_name(byte *buf)
67 {
68   static int cnt;
69   sprintf(buf, "%s%d-%d", temp_prefix, (int)getpid(), cnt++);
70 }
71
72 #endif
73
74 struct fastbuf *
75 bopen_tmp(uns buflen)
76 {
77   byte buf[TEMP_FILE_NAME_LEN];
78   struct fastbuf *f;
79
80   temp_file_name(buf);
81   f = bopen(buf, O_RDWR | O_CREAT | O_TRUNC, buflen);
82   bconfig(f, BCONFIG_IS_TEMP_FILE, 1);
83   return f;
84 }
85
86 #ifdef TEST
87
88 #include "lib/getopt.h"
89
90 int main(int argc, char **argv)
91 {
92   log_init(NULL);
93   if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0)
94     die("Hey, whaddya want?");
95
96   struct fastbuf *f = bopen_tmp(65536);
97   bputsn(f, "Hello, world!");
98   bclose(f);
99   return 0;
100 }
101
102 #endif