lock-util: Add unposix_lock()

Let's add an interface to UNPOSIX locks that mimicks the flock()
interface for BSD locks.
This commit is contained in:
Daan De Meyer
2023-03-10 11:57:40 +01:00
parent 64e89f56a9
commit 663fd3e103
2 changed files with 37 additions and 0 deletions
+34
View 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;
}
+3
View 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);