+static int
+lkopen_lockf(const char *file, int access, mode_t mode, int *failed_to_lock)
+{
+ int fd, i, saved_errno, saved_access;
+
+ /*
+ * Two notes:
+ *
+ * Because lockf locks start from the current offset, mask off O_APPEND
+ * and seek to the end of the file later if it was requested.
+ *
+ * lockf locks require write access to the file, so always add it
+ * even if it wasn't requested.
+ */
+
+ saved_access = access;
+
+ access &= ~O_APPEND;
+
+ if ((access & O_ACCMODE) == O_RDONLY) {
+ access &= ~O_RDONLY;
+ access |= O_RDWR;
+ }
+
+ for (i = 0; i < LOCK_RETRIES; i++) {
+ if ((fd = open(file, access, mode)) == -1)
+ return -1;
+
+ if (lockf(fd, F_TLOCK, 0) != -1) {
+ /*
+ * Seek to end if requested
+ */
+ if (saved_access & O_APPEND) {
+ lseek(fd, 0, SEEK_END);
+ }
+ return fd;
+ }
+
+ saved_errno = errno;
+ close(fd);
+ sleep(1);
+ }
+
+ *failed_to_lock = 1;
+ errno = saved_errno;
+ return -1;
+}