Implement {lock,unlock}repo() - dedup - deduplicating backup program HTML git clone git://bitreich.org/dedup/ git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65d7roiv6bfj7d652fid.onion/dedup/ DIR Log DIR Files DIR Refs DIR Tags DIR README DIR LICENSE --- DIR commit 2fcad321a15f6d09e77b70650e9737bd2d370a6e DIR parent 3a24ddb8e397799f7af86d11941bd9c7e73470fd HTML Author: sin <sin@2f30.org> Date: Sun, 5 May 2019 17:34:48 +0100 Implement {lock,unlock}repo() Diffstat: M Makefile | 2 ++ A lock.c | 55 +++++++++++++++++++++++++++++++ A lock.h | 2 ++ 3 files changed, 59 insertions(+), 0 deletions(-) --- DIR diff --git a/Makefile b/Makefile @@ -9,6 +9,7 @@ HDR = \ chunker.h \ config.h \ key.h \ + lock.h \ misc.h \ queue.h \ snap.h \ @@ -22,6 +23,7 @@ COMMOBJ = \ bstorage.o \ chunker.o \ key.o \ + lock.o \ misc.o \ pack.o \ snap.o \ DIR diff --git a/lock.c b/lock.c @@ -0,0 +1,55 @@ +#include <fcntl.h> +#include <limits.h> +#include <stdio.h> +#include <unistd.h> + +int +lockrepo(char *repo) +{ + char path[PATH_MAX]; + struct flock fl; + int fd; + + if (snprintf(path, sizeof(path), "%s/lock", repo) >= + sizeof(path)) + return -1; + + fd = open(path, O_RDWR | O_CREAT, 0600); + if (fd < 0) + return -1; + + fl.l_type = F_WRLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + if (fcntl(fd, F_SETLK, &fl) < 0) { + close(fd); + return -1; + } + return fd; +} + +int +unlockrepo(char *repo, int fd) +{ + char path[PATH_MAX]; + struct flock fl; + + if (snprintf(path, sizeof(path), "%s/lock", repo) >= + sizeof(path)) + return -1; + + if (unlink(path) < 0) + return -1; + + fl.l_type = F_UNLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + if (fcntl(fd, F_SETLK, &fl) < 0) + return -1; + + if (close(fd) < 0) + return -1; + return 0; +} DIR diff --git a/lock.h b/lock.h @@ -0,0 +1,2 @@ +int lockrepo(char *); +int unlockrepo(char *, int);