X-Git-Url: http://git.ozlabs.org/?a=blobdiff_plain;f=tools%2Ftools.c;h=87ff4a3b65f4fe9899cf8aebb6e99a40cd244221;hb=32a31d9e4fb1f312a47ae8c237ac30d6c1567ccd;hp=d50a67fd18256b0ab3668018d84e0db429b85477;hpb=61088f5c752c555172e2ab6cf93a7967f79f3f2c;p=ccan diff --git a/tools/tools.c b/tools/tools.c index d50a67fd..87ff4a3b 100644 --- a/tools/tools.c +++ b/tools/tools.c @@ -1,11 +1,17 @@ #include #include +#include +#include #include #include #include #include +#include #include "tools.h" +static char *tmpdir = NULL; +static unsigned int count; + char *talloc_basename(const void *ctx, const char *dir) { char *p = strrchr(dir, '/'); @@ -42,6 +48,7 @@ char *talloc_getcwd(const void *ctx) return cwd; } +/* Returns output if command fails. */ char *run_command(const void *ctx, const char *fmt, ...) { va_list ap; @@ -54,7 +61,7 @@ char *run_command(const void *ctx, const char *fmt, ...) /* Ensure stderr gets to us too. */ cmd = talloc_asprintf_append(cmd, " 2>&1"); - + pipe = popen(cmd, "r"); if (!pipe) return talloc_asprintf(ctx, "Failed to run '%s'", cmd); @@ -67,3 +74,36 @@ char *run_command(const void *ctx, const char *fmt, ...) talloc_free(cmd); return NULL; } + +static int unlink_all(char *dir) +{ + char cmd[strlen(dir) + sizeof("rm -rf ")]; + sprintf(cmd, "rm -rf %s", dir); + if (system(cmd) != 0) + warn("Could not remove temporary work in %s", dir); + return 0; +} + +char *temp_file(const void *ctx, const char *extension) +{ + /* For first call, create dir. */ + while (!tmpdir) { + tmpdir = getenv("TMPDIR"); + if (!tmpdir) + tmpdir = "/tmp"; + tmpdir = talloc_asprintf(talloc_autofree_context(), + "%s/ccanlint-%u.%lu", + tmpdir, getpid(), random()); + if (mkdir(tmpdir, 0700) != 0) { + if (errno == EEXIST) { + talloc_free(tmpdir); + tmpdir = NULL; + continue; + } + err(1, "mkdir %s failed", tmpdir); + } + talloc_set_destructor(tmpdir, unlink_all); + } + + return talloc_asprintf(ctx, "%s/%u%s", tmpdir, count++, extension); +}