]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
lock-util: Add posix_lock()
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 13 Mar 2023 12:03:32 +0000 (13:03 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 13 Mar 2023 12:04:08 +0000 (13:04 +0100)
POSIX locks with the same interface as flock().

src/basic/lock-util.c
src/basic/lock-util.h

index ba0c23445beb38ea1652765b195d6798928dcd6b..c7a7b68ebcf2919b2fccd6cdcfe399cda2690587 100644 (file)
@@ -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;
 }
index e8d4c24874f11b210e8aee8901d34ee67cb457ae..6eebd0914350570d1a701d52db4db6bce555a638 100644 (file)
@@ -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)                                   \