X-Git-Url: https://git.ozlabs.org/?p=ccan;a=blobdiff_plain;f=tools%2Ftools.c;h=18cc1b84cb299fcc8c5659a05b6c6c05da701a82;hp=2da37234e2dd034ea8d5dd0f108eadcb8caf86bf;hb=a879e3e2859e17496f29e14b8f393583b2c93f19;hpb=3612661714e86333ceacca7314959a5ed938dc6a diff --git a/tools/tools.c b/tools/tools.c index 2da37234..18cc1b84 100644 --- a/tools/tools.c +++ b/tools/tools.c @@ -1,7 +1,10 @@ #include #include +#include +#include #include #include +#include #include #include #include @@ -61,7 +64,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); @@ -79,7 +82,8 @@ static int unlink_all(char *dir) { char cmd[strlen(dir) + sizeof("rm -rf ")]; sprintf(cmd, "rm -rf %s", dir); -// system(cmd); + if (system(cmd) != 0) + warn("Could not remove temporary work in %s", dir); return 0; } @@ -106,3 +110,39 @@ char *temp_file(const void *ctx, const char *extension) return talloc_asprintf(ctx, "%s/%u%s", tmpdir, count++, extension); } + +bool move_file(const char *oldname, const char *newname) +{ + char *contents; + size_t size; + int fd; + bool ret; + + /* Simple case: rename works. */ + if (rename(oldname, newname) == 0) + return true; + + /* Try copy and delete: not atomic! */ + contents = grab_file(NULL, oldname, &size); + if (!contents) + return false; + + fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666); + if (fd < 0) { + ret = false; + goto free; + } + + ret = write_all(fd, contents, size); + if (close(fd) != 0) + ret = false; + + if (ret) + unlink(oldname); + else + unlink(newname); + +free: + talloc_free(contents); + return ret; +}