From 01dbecb2e93aa782685c87021a1bc6912b810c4d Mon Sep 17 00:00:00 2001 From: Calvin Morrison Date: Thu, 10 Apr 2014 11:16:07 -0400 Subject: c version of lock --- lock.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 lock.c (limited to 'lock.c') diff --git a/lock.c b/lock.c new file mode 100644 index 0000000..12d560b --- /dev/null +++ b/lock.c @@ -0,0 +1,54 @@ +/* See LICENSE for licence details. */ + +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv){ + size_t pathlen, argvlen; + char *path; + + if(argc != 2){ + fprintf(stderr, "Please supply one argument: the lock directory.\n"); + return EXIT_FAILURE; + } + + if(access(argv[1], F_OK)){ + /* create lock */ + if(mkdir(argv[1], S_IRUSR | S_IXUSR)){ + fprintf(stderr, "Failed to create lock %s.\n", argv[1]); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; + } + + /* prepare path */ + argvlen = strlen(argv[1]); + pathlen = argvlen + sizeof("/..") + 1; + path = malloc(pathlen); + if(path == NULL) { + fprintf(stderr, "Error: %s\n", strerror(errno)); + return EXIT_FAILURE; + } + + memcpy(path, argv[1], argvlen); + memcpy(path + argvlen, "/..\0", sizeof("/..") + 1); + + if(access(path, F_OK)){ + /* invalid lock */ + fprintf(stderr, "%s is not a lock directory.\n", argv[1]); + free(path); + return EXIT_FAILURE; + } + + /* lock exists */ + for(; !access(path, F_OK) ;){ + sleep(1); + } + + free(path); + return EXIT_SUCCESS; +} -- cgit v1.2.3