X-Git-Url: http://mj.ucw.cz/gitweb/?a=blobdiff_plain;f=lib%2Ffb-temp.c;h=1975c8cc3f62c9c31b63d1863beb937591dd1b40;hb=c4bf633211b0424492b5a3937d6a6d2e0d79a4cf;hp=a537dd934f7b7541068b006014f0c559bedf6f79;hpb=93cdcca9ba4018c094c558418a120928f2ab32ee;p=libucw.git diff --git a/lib/fb-temp.c b/lib/fb-temp.c index a537dd93..1975c8cc 100644 --- a/lib/fb-temp.c +++ b/lib/fb-temp.c @@ -1,7 +1,7 @@ /* - * Sherlock Library -- Temporary Fastbufs + * UCW Library -- Temporary Fastbufs * - * (c) 2002--2004 Martin Mares + * (c) 2002--2007 Martin Mares * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. @@ -10,32 +10,77 @@ #include "lib/lib.h" #include "lib/conf.h" #include "lib/fastbuf.h" +#include "lib/threads.h" +#include #include #include -static byte *temp_template = "/tmp/temp%d.%d"; +static char *temp_prefix = "/tmp/temp"; -static struct cfitem temp_config[] = { - { "Tempfiles", CT_SECTION, NULL }, - { "Template", CT_STRING, &temp_template }, - { NULL, CT_STOP, NULL } +static struct cf_section temp_config = { + CF_ITEMS { + CF_STRING("Prefix", &temp_prefix), + CF_END + } }; -static void CONSTRUCTOR temp_init_config(void) +static void CONSTRUCTOR temp_global_init(void) { - cf_register(temp_config); + cf_declare_section("Tempfiles", &temp_config, 0); +} + +void +temp_file_name(char *buf) +{ + struct ucwlib_context *ctx = ucwlib_thread_context(); + int cnt = ++ctx->temp_counter; + int pid = getpid(); + if (ctx->thread_id == pid) + sprintf(buf, "%s%d-%d", temp_prefix, pid, cnt); + else + sprintf(buf, "%s%d-%d-%d", temp_prefix, pid, ctx->thread_id, cnt); } struct fastbuf * -bopen_tmp(uns bufsize) +bopen_tmp_file(struct fb_params *params) { - byte buf[256]; - struct fastbuf *f; - static uns temp_counter; - - sprintf(buf, temp_template, (int) getpid(), temp_counter++); - f = bopen(buf, O_RDWR | O_CREAT | O_TRUNC, bufsize); - bconfig(f, BCONFIG_IS_TEMP_FILE, 1); - return f; + 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; } + +struct fastbuf * +bopen_tmp(uns buflen) +{ + return bopen_tmp_file(&(struct fb_params){ .type = FB_STD, .buffer_size = buflen }); +} + +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 + +#include "lib/getopt.h" + +int main(int argc, char **argv) +{ + log_init(NULL); + if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) >= 0) + die("Hey, whaddya want?"); + + struct fastbuf *f = bopen_tmp(65536); + bputsn(f, "Hello, world!"); + bclose(f); + return 0; +} + +#endif