]> git.ipfire.org Git - thirdparty/libbsd.git/commitdiff
Use lockf() when flock() is not available
authorGuillem Jover <guillem@hadrons.org>
Mon, 10 Apr 2023 21:10:40 +0000 (23:10 +0200)
committerGuillem Jover <guillem@hadrons.org>
Mon, 17 Apr 2023 02:12:42 +0000 (04:12 +0200)
On Solaris flock() is not available, and we should use instead lockf()
or fcntl().

configure.ac
src/flopen.c

index 78a4c9764e09f4c27a4e8d2bf585b02ebeecbad0..17978b18c07078587346894963f361514b43575e 100644 (file)
@@ -290,6 +290,7 @@ __register_atfork(NULL, NULL, NULL, __dso_handle);
 AC_CHECK_FUNCS([\
   clearenv \
   dirfd \
+  flock \
   fopencookie \
   __fpurge \
   getauxval \
index ff20d074445b03ec25a18c13972cd590d9120d94..679445f4947676d632eb280949f9761698da39a2 100644 (file)
 
 #include <libutil.h>
 
+static int
+lock_file(int fd, int flags)
+{
+       int operation;
+
+#if HAVE_FLOCK
+       operation = LOCK_EX;
+       if (flags & O_NONBLOCK)
+               operation |= LOCK_NB;
+
+       return flock(fd, operation);
+#else
+       if (flags & O_NONBLOCK)
+               operation = F_TLOCK;
+       else
+               operation = F_LOCK;
+
+       return lockf(fd, operation, 0);
+#endif
+}
+
 /*
  * Reliably open and lock a file.
  *
@@ -49,7 +70,7 @@
 static int
 vflopenat(int dirfd, const char *path, int flags, va_list ap)
 {
-       int fd, operation, serrno, trunc;
+       int fd, serrno, trunc;
        struct stat sb, fsb;
        mode_t mode;
 
@@ -62,10 +83,6 @@ vflopenat(int dirfd, const char *path, int flags, va_list ap)
                mode = (mode_t)va_arg(ap, int); /* mode_t promoted to int */
        }
 
-        operation = LOCK_EX;
-        if (flags & O_NONBLOCK)
-                operation |= LOCK_NB;
-
        trunc = (flags & O_TRUNC);
        flags &= ~O_TRUNC;
 
@@ -73,7 +90,7 @@ vflopenat(int dirfd, const char *path, int flags, va_list ap)
                if ((fd = openat(dirfd, path, flags, mode)) == -1)
                        /* non-existent or no access */
                        return (-1);
-               if (flock(fd, operation) == -1) {
+               if (lock_file(fd, flags) == -1) {
                        /* unsupported or interrupted */
                        serrno = errno;
                        (void)close(fd);