]> mj.ucw.cz Git - libucw.git/blobdiff - lib/fb-temp.c
bgetl() should return uns instead of u32
[libucw.git] / lib / fb-temp.c
index ed7623ffc85edc5989678a5be0106c5124064881..1975c8cc3f62c9c31b63d1863beb937591dd1b40 100644 (file)
@@ -1,7 +1,7 @@
 /*
  *     UCW Library -- Temporary Fastbufs
  *
- *     (c) 2002--2006 Martin Mares <mj@ucw.cz>
+ *     (c) 2002--2007 Martin Mares <mj@ucw.cz>
  *
  *     This software may be freely distributed and used according to the terms
  *     of the GNU Lesser General Public License.
 #include "lib/lib.h"
 #include "lib/conf.h"
 #include "lib/fastbuf.h"
+#include "lib/threads.h"
 
+#include <stdio.h>
 #include <unistd.h>
 #include <sys/fcntl.h>
 
-static byte *temp_prefix = "/tmp/temp";
+static char *temp_prefix = "/tmp/temp";
 
 static struct cf_section temp_config = {
   CF_ITEMS {
@@ -28,59 +30,41 @@ static void CONSTRUCTOR temp_global_init(void)
   cf_declare_section("Tempfiles", &temp_config, 0);
 }
 
-#ifdef CONFIG_UCW_THREADS
-#include <pthread.h>
-
-static pthread_key_t temp_counter_key;
-
-static void CONSTRUCTOR
-temp_key_init(void)
-{
-  if (pthread_key_create(&temp_counter_key, NULL) < 0)
-    die("Cannot create fbdir_queue_key: %m");
-}
-
 void
-temp_file_name(byte *buf)
+temp_file_name(char *buf)
 {
-  int cnt = (int) pthread_getspecific(temp_counter_key);
-  cnt++;
-  pthread_setspecific(temp_counter_key, (void *) cnt);
-
+  struct ucwlib_context *ctx = ucwlib_thread_context();
+  int cnt = ++ctx->temp_counter;
   int pid = getpid();
-#if 0
-  /* FIXME: This is Linux-specific and not declared anywhere :( */
-  int tid = gettid();
-#else
-  int tid = pid;
-#endif
-  if (pid == tid)
+  if (ctx->thread_id == pid)
     sprintf(buf, "%s%d-%d", temp_prefix, pid, cnt);
   else
-    sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, tid, cnt);
+    sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, ctx->thread_id, cnt);
 }
 
-#else
-
-void
-temp_file_name(byte *buf)
+struct fastbuf *
+bopen_tmp_file(struct fb_params *params)
 {
-  static int cnt;
-  sprintf(buf, "%s%d-%d", temp_prefix, (int)getpid(), cnt++);
+  char name[TEMP_FILE_NAME_LEN];
+  temp_file_name(name);
+  struct fastbuf *fb = bopen_file(name, O_RDWR | O_CREAT | O_TRUNC, params);
+  bconfig(fb, BCONFIG_IS_TEMP_FILE, 1);
+  return fb;
 }
 
-#endif
-
 struct fastbuf *
 bopen_tmp(uns buflen)
 {
-  byte buf[TEMP_FILE_NAME_LEN];
-  struct fastbuf *f;
+  return bopen_tmp_file(&(struct fb_params){ .type = FB_STD, .buffer_size = buflen });
+}
 
-  temp_file_name(buf);
-  f = bopen(buf, O_RDWR | O_CREAT | O_TRUNC, buflen);
-  bconfig(f, BCONFIG_IS_TEMP_FILE, 1);
-  return f;
+void bfix_tmp_file(struct fastbuf *fb, const char *name)
+{
+  int was_temp = bconfig(fb, BCONFIG_IS_TEMP_FILE, 0);
+  ASSERT(was_temp == 1);
+  if (rename(fb->name, name))
+    die("Cannot rename %s to %s: %m", fb->name, name);
+  bclose(fb);
 }
 
 #ifdef TEST