tmus

TUI Music Player
git clone https://git.sinitax.com/sinitax/tmus
Log | Files | Refs | Submodules | LICENSE | sfeed.txt

commit 38eb5ec7b286085b505b4cd088c2b9638eb5ae00
parent 57d4fc4d9d60654f2c1a7253ac5f0ee11f103cf9
Author: Louis Burda <quent.burda@gmail.com>
Date:   Tue,  1 Mar 2022 15:02:40 +0100

Added lock for data directory

Diffstat:
Msrc/data.c | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/data.h | 4++++
2 files changed, 74 insertions(+), 0 deletions(-)

diff --git a/src/data.c b/src/data.c @@ -172,6 +172,12 @@ tracks_save(struct tag *tag) } bool +path_exists(const char *path) +{ + return access(path, F_OK) == 0; +} + +bool make_dir(const char *path) { return mkdir(path, S_IRWXU | S_IRWXG) == 0; @@ -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 @@ -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);