diff options
author | Daan De Meyer <daan.j.demeyer@gmail.com> | 2023-03-13 13:03:32 +0100 |
---|---|---|
committer | Daan De Meyer <daan.j.demeyer@gmail.com> | 2023-03-13 13:04:08 +0100 |
commit | 846c9c12e75e832e41a6c21ee818f6726c142214 (patch) | |
tree | ae86f7c670737fe7061b1ae19333e21bb0c4aaf6 | |
parent | dcebb015fb168351039ab0c89f49f485503deeb0 (diff) | |
download | systemd-846c9c12e75e832e41a6c21ee818f6726c142214.tar.gz |
lock-util: Add posix_lock()
POSIX locks with the same interface as flock().
-rw-r--r-- | src/basic/lock-util.c | 27 | ||||
-rw-r--r-- | src/basic/lock-util.h | 8 |
2 files changed, 31 insertions, 4 deletions
diff --git a/src/basic/lock-util.c b/src/basic/lock-util.c index ba0c23445b..c7a7b68ebc 100644 --- a/src/basic/lock-util.c +++ b/src/basic/lock-util.c @@ -109,12 +109,15 @@ void release_lock_file(LockFile *f) { f->operation = 0; } -int unposix_lock(int fd, int operation) { +static int fcntl_lock(int fd, int operation, bool ofd) { int cmd, type, r; assert(fd >= 0); - cmd = (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW; + if (ofd) + cmd = (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW; + else + cmd = (operation & LOCK_NB) ? F_SETLK : F_SETLKW; switch (operation & ~LOCK_NB) { case LOCK_EX: @@ -143,12 +146,30 @@ int unposix_lock(int fd, int operation) { return r; } +int posix_lock(int fd, int operation) { + return fcntl_lock(fd, operation, /*ofd=*/ false); +} + +int unposix_lock(int fd, int operation) { + return fcntl_lock(fd, operation, /*ofd=*/ true); +} + +void posix_unlockpp(int **fd) { + assert(fd); + + if (!*fd || **fd < 0) + return; + + (void) fcntl_lock(**fd, LOCK_UN, /*ofd=*/ false); + *fd = NULL; +} + void unposix_unlockpp(int **fd) { assert(fd); if (!*fd || **fd < 0) return; - (void) unposix_lock(**fd, LOCK_UN); + (void) fcntl_lock(**fd, LOCK_UN, /*ofd=*/ true); *fd = NULL; } diff --git a/src/basic/lock-util.h b/src/basic/lock-util.h index e8d4c24874..6eebd09143 100644 --- a/src/basic/lock-util.h +++ b/src/basic/lock-util.h @@ -13,9 +13,15 @@ void release_lock_file(LockFile *f); #define LOCK_FILE_INIT { .fd = -EBADF, .path = NULL } +/* POSIX locks with the same interface as flock(). */ +int posix_lock(int fd, int operation); +void posix_unlockpp(int **fd); + +#define CLEANUP_POSIX_UNLOCK(fd) \ + _cleanup_(posix_unlockpp) _unused_ int *CONCATENATE(_cleanup_posix_unlock_, UNIQ) = &(fd) + /* Open File Description locks with the same interface as flock(). */ int unposix_lock(int fd, int operation); - void unposix_unlockpp(int **fd); #define CLEANUP_UNPOSIX_UNLOCK(fd) \ |