From 38eb5ec7b286085b505b4cd088c2b9638eb5ae00 Mon Sep 17 00:00:00 2001 From: Louis Burda Date: Tue, 1 Mar 2022 15:02:40 +0100 Subject: Added lock for data directory --- src/data.c | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/data.h | 4 ++++ 2 files changed, 74 insertions(+) (limited to 'src') diff --git a/src/data.c b/src/data.c index 2ba102f..d8768b9 100644 --- a/src/data.c +++ b/src/data.c @@ -171,6 +171,12 @@ tracks_save(struct tag *tag) free(index_path); } +bool +path_exists(const char *path) +{ + return access(path, F_OK) == 0; +} + bool make_dir(const char *path) { @@ -493,6 +499,65 @@ track_rm(struct track *track, bool sync_fs) return true; } +bool +aquire_lock(const char *datadir) +{ + char *lockpath, *procpath; + char linebuf[512]; + FILE *file; + int pid; + + lockpath = aprintf("%s/.lock", datadir); + OOM_CHECK(lockpath); + + if (path_exists(lockpath)) { + file = fopen(lockpath, "r"); + if (file == NULL) { + free(lockpath); + return false; + } + + fread(linebuf, 1, sizeof(linebuf), file); + pid = atoi(linebuf); + procpath = aprintf("/proc/%i", pid); + OOM_CHECK(procpath); + if (path_exists(procpath)) { + free(procpath); + free(lockpath); + return false; + } + free(procpath); + + fclose(file); + } + + file = fopen(lockpath, "w+"); + if (file == NULL) return false; + snprintf(linebuf, sizeof(linebuf), "%i", getpid()); + fputs(linebuf, file); + fclose(file); + + free(lockpath); + + return true; +} + +bool +release_lock(const char *datadir) +{ + char *lockpath; + bool status; + + lockpath = aprintf("%s/.lock", datadir); + OOM_CHECK(lockpath); + + status = rm_file(lockpath); + + free(lockpath); + + return status; +} + void data_load(void) { @@ -509,6 +574,9 @@ data_load(void) datadir = getenv("TMUS_DATA"); if (!datadir) ERROR("TMUS_DATA not set!\n"); + if (!aquire_lock(datadir)) + ERROR("Failed to acquire lock\n"); + dir = opendir(datadir); if (!dir) ERROR("Failed to access dir: %s\n", datadir); @@ -542,6 +610,8 @@ data_save(void) tag = UPCAST(link, struct tag, link); tracks_save(tag); } + + release_lock(datadir); } void diff --git a/src/data.h b/src/data.h index 63f2f64..7c5c92b 100644 --- a/src/data.h +++ b/src/data.h @@ -23,6 +23,7 @@ struct track { struct link link_hs; /* player history */ }; +bool path_exists(const char *path); bool make_dir(const char *path); bool rm_dir(const char *path, bool recursive); bool rm_file(const char *path); @@ -45,6 +46,9 @@ bool tag_rm(struct tag *tag, bool sync_fs); struct track *track_add(struct tag *tag, const char *fname); bool track_rm(struct track *track, bool sync_fs); +bool acquire_lock(const char *path); +bool release_lock(const char *path); + void data_load(void); void data_save(void); void data_free(void); -- cgit v1.2.3-71-gd317