X-Git-Url: http://git.ozlabs.org/?p=ccan;a=blobdiff_plain;f=tools%2Ftools.c;h=8ce193cd226bd0905f7a6738c4f70eda4057fe1c;hp=6e19f96128b0eb624e2f2d8edaa85e28f24e2c43;hb=bbd7380019f3ea4629d170af24b902bf734c83ea;hpb=304652023042670b3173de0ad5dc0eb7c836618c;ds=sidebyside diff --git a/tools/tools.c b/tools/tools.c index 6e19f961..8ce193cd 100644 --- a/tools/tools.c +++ b/tools/tools.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "tools.h" static char *tmpdir = NULL; @@ -57,6 +58,11 @@ char *talloc_getcwd(const void *ctx) return cwd; } +static void killme(int sig) +{ + kill(-getpid(), SIGKILL); +} + static char *run_with_timeout(const void *ctx, const char *cmd, bool *ok, @@ -73,6 +79,7 @@ static char *run_with_timeout(const void *ctx, return talloc_asprintf(ctx, "Failed to create pipe: %s", strerror(errno)); + gettimeofday(&start, NULL); pid = fork(); if (pid == -1) { close_noerr(p[0]); @@ -92,6 +99,7 @@ static char *run_with_timeout(const void *ctx, || open("/dev/null", O_RDONLY) != STDIN_FILENO) exit(128); + signal(SIGALRM, killme); itim.it_interval.tv_sec = itim.it_interval.tv_usec = 0; itim.it_value.tv_sec = *timeout_ms / 1000; itim.it_value.tv_usec = (*timeout_ms % 1000) * 1000; @@ -105,17 +113,12 @@ static char *run_with_timeout(const void *ctx, } close(p[1]); - gettimeofday(&start, NULL); ret = grab_fd(ctx, p[0], NULL); /* This shouldn't fail... */ if (waitpid(pid, &status, 0) != pid) err(1, "Failed to wait for child"); gettimeofday(&end, NULL); - if (WIFSIGNALED(status)) { - *timeout_ms = 0; - return ret; - } if (end.tv_usec < start.tv_usec) { end.tv_usec += 1000000; end.tv_sec--; @@ -127,7 +130,7 @@ static char *run_with_timeout(const void *ctx, else *timeout_ms -= ms; - *ok = (WEXITSTATUS(status) == 0); + *ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0); return ret; } @@ -141,6 +144,8 @@ char *run_command(const void *ctx, unsigned int *time_ms, const char *fmt, ...) if (!time_ms) time_ms = &default_time; + else if (*time_ms == 0) + return talloc_strdup(ctx, "\n== TIMED OUT ==\n"); va_start(ap, fmt); cmd = talloc_vasprintf(ctx, fmt, ap); @@ -155,7 +160,8 @@ char *run_command(const void *ctx, unsigned int *time_ms, const char *fmt, ...) if (!contents) err(1, "Problem running child"); if (*time_ms == 0) - talloc_asprintf_append(contents, "\n== TIMED OUT ==\n"); + contents = talloc_asprintf_append(contents, + "\n== TIMED OUT ==\n"); return contents; } @@ -192,6 +198,18 @@ char *temp_file(const void *ctx, const char *extension) return talloc_asprintf(ctx, "%s/%u%s", tmpdir, count++, extension); } +char *maybe_temp_file(const void *ctx, const char *extension, bool keep, + const char *srcname) +{ + size_t baselen; + + if (!keep) + return temp_file(ctx, extension); + + baselen = strrchr(srcname, '.') - srcname; + return talloc_asprintf(ctx, "%.*s%s", baselen, srcname, extension); +} + bool move_file(const char *oldname, const char *newname) { char *contents;