From: Daan De Meyer Date: Thu, 9 Mar 2023 11:16:54 +0000 (+0100) Subject: lock-util: Add unposix_lock() X-Git-Tag: v254-rc1~1066^2~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=663fd3e103a1d9b1dbc77ada9db7901f24338dab;p=thirdparty%2Fsystemd.git lock-util: Add unposix_lock() Let's add an interface to UNPOSIX locks that mimicks the flock() interface for BSD locks. --- diff --git a/src/shared/lock-util.c b/src/shared/lock-util.c index 81bdc03bc89..bbbd3146437 100644 --- a/src/shared/lock-util.c +++ b/src/shared/lock-util.c @@ -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; +} diff --git a/src/shared/lock-util.h b/src/shared/lock-util.h index 20e19c01d4d..66f86351331 100644 --- a/src/shared/lock-util.h +++ b/src/shared/lock-util.h @@ -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);