]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
lock-util: Add unposix_lock()
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Thu, 9 Mar 2023 11:16:54 +0000 (12:16 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Fri, 10 Mar 2023 10:57:40 +0000 (11:57 +0100)
Let's add an interface to UNPOSIX locks that mimicks the flock()
interface for BSD locks.

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

index 81bdc03bc892967511c4d9660a4f979f2b938c00..bbbd31464377e4912b6811e9f43b546ca89a663b 100644 (file)
@@ -115,3 +115,37 @@ void release_lock_file(LockFile *f) {
         f->fd = safe_close(f->fd);
         f->operation = 0;
 }
+
+int unposix_lock(int fd, int operation) {
+        int cmd, type, r;
+
+        assert(fd >= 0);
+
+        cmd = (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW;
+
+        switch (operation & ~LOCK_NB) {
+                case LOCK_EX:
+                        type = F_WRLCK;
+                        break;
+                case LOCK_SH:
+                        type = F_RDLCK;
+                        break;
+                case LOCK_UN:
+                        type = F_UNLCK;
+                        break;
+                default:
+                        assert_not_reached();
+        }
+
+        r = RET_NERRNO(fcntl(fd, cmd, &(struct flock) {
+                .l_type = type,
+                .l_whence = SEEK_SET,
+                .l_start = 0,
+                .l_len = 0,
+        }));
+
+        if (r == -EACCES) /* Treat EACCESS/EAGAIN the same as per man page. */
+                r = -EAGAIN;
+
+        return r;
+}
index 20e19c01d4d3e114e9cb9a4d0301228dbc0d6689..66f86351331c7a1fe21729c8acd5721347944ad4 100644 (file)
@@ -12,3 +12,6 @@ int make_lock_file_for(const char *p, int operation, LockFile *ret);
 void release_lock_file(LockFile *f);
 
 #define LOCK_FILE_INIT { .fd = -EBADF, .path = NULL }
+
+/* Open File Description locks with the same interface as flock(). */
+int unposix_lock(int fd, int operation);