summaryrefslogtreecommitdiff
path: root/src/lib/lockfile.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/lockfile.c')
-rw-r--r--src/lib/lockfile.c98
1 files changed, 42 insertions, 56 deletions
diff --git a/src/lib/lockfile.c b/src/lib/lockfile.c
index b0e1115f..cf6d3c94 100644
--- a/src/lib/lockfile.c
+++ b/src/lib/lockfile.c
@@ -1,5 +1,5 @@
/*
- * Ouroboros - Copyright (C) 2016 - 2021
+ * Ouroboros - Copyright (C) 2016 - 2024
*
* Lockfile for Ouroboros
*
@@ -36,81 +36,69 @@
#include <sys/stat.h>
#define LF_SIZE (sizeof(pid_t))
+#define LF_PROT (PROT_READ | PROT_WRITE)
struct lockfile {
pid_t * pid;
};
-struct lockfile * lockfile_create() {
- int fd;
- mode_t mask;
- struct lockfile * lf = malloc(sizeof(*lf));
- if (lf == NULL)
- return NULL;
-
- mask = umask(0);
+static struct lockfile * __lockfile_open(int oflag)
+{
+ int fd;
+ struct lockfile * lf;
- fd = shm_open(SHM_LOCKFILE_NAME, O_CREAT | O_EXCL | O_RDWR, 0666);
- if (fd == -1) {
- free(lf);
- return NULL;
- }
+ lf = malloc(sizeof(*lf));
+ if (lf == NULL)
+ goto fail_lockfile;
- umask(mask);
+ fd = shm_open(SHM_LOCKFILE_NAME, oflag, 0666);
+ if (fd == -1)
+ goto fail_shm_open;
- if (ftruncate(fd, LF_SIZE - 1) < 0) {
- free(lf);
- return NULL;
- }
+ if ((oflag & O_CREAT) && ftruncate(fd, LF_SIZE) < 0)
+ goto fail_truncate;
- lf->pid = mmap(NULL,
- LF_SIZE, PROT_READ | PROT_WRITE,
- MAP_SHARED,
- fd,
- 0);
+ lf->pid = mmap(NULL, LF_SIZE, LF_PROT, MAP_SHARED, fd, 0);
+ if (lf->pid == MAP_FAILED)
+ goto fail_mmap;
close (fd);
- if (lf->pid == MAP_FAILED) {
- shm_unlink(SHM_LOCKFILE_NAME);
- free(lf);
- return NULL;
- }
-
- *lf->pid = getpid();
-
return lf;
+
+ fail_mmap:
+ shm_unlink(SHM_LOCKFILE_NAME);
+ fail_truncate:
+ close(fd);
+ fail_shm_open:
+ free(lf);
+ fail_lockfile:
+ return NULL;
}
-struct lockfile * lockfile_open() {
- int fd;
- struct lockfile * lf = malloc(sizeof(*lf));
- if (lf == NULL)
- return NULL;
+struct lockfile * lockfile_create(void)
+{
+ struct lockfile * lf;
+ mode_t mask;
- fd = shm_open(SHM_LOCKFILE_NAME, O_RDWR, 0666);
- if (fd < 0) {
- free(lf);
- return NULL;
- }
+ mask = umask(0);
- lf->pid = mmap(NULL,
- LF_SIZE, PROT_READ | PROT_WRITE,
- MAP_SHARED,
- fd,
- 0);
+ lf = __lockfile_open(O_CREAT | O_EXCL | O_RDWR);
+ if (lf == NULL)
+ return NULL;
- close(fd);
+ umask(mask);
- if (lf->pid == MAP_FAILED) {
- shm_unlink(SHM_LOCKFILE_NAME);
- free(lf);
- return NULL;
- }
+ *lf->pid = getpid();
return lf;
}
+struct lockfile * lockfile_open(void)
+{
+ return __lockfile_open(O_RDWR);
+}
+
void lockfile_close(struct lockfile * lf)
{
assert(lf);
@@ -127,11 +115,9 @@ void lockfile_destroy(struct lockfile * lf)
if (getpid() != *lf->pid && kill(*lf->pid, 0) == 0)
return;
- munmap(lf->pid, LF_SIZE);
+ lockfile_close(lf);
shm_unlink(SHM_LOCKFILE_NAME);
-
- free(lf);
}
pid_t lockfile_owner(struct lockfile * lf)