2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2018 The OpenLDAP Foundation.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted only as authorized by the OpenLDAP
11 * A copy of this license is available in the file LICENSE in the
12 * top-level directory of the distribution or, alternatively, at
13 * <http://www.OpenLDAP.org/license.html>.
17 * File Locking Routines
19 * Implementations (in order of preference)
24 * Other implementations will be added as needed.
26 * NOTE: lutil_lockf() MUST block until an exclusive lock is acquired.
32 #include <ac/unistd.h>
36 #if defined(HAVE_LOCKF) && defined(F_LOCK)
38 # define LOCK_API "lockf"
41 #if !defined(LOCK_API) && defined(HAVE_FCNTL)
47 # define LOCK_API "fcntl"
51 #if !defined(LOCK_API) && defined(HAVE_FLOCK)
52 # ifdef HAVE_SYS_FILE_H
53 # include <sys/file.h>
56 # define LOCK_API "flock"
59 #if !defined(USE_LOCKF) && !defined(USE_FCNTL) && !defined(USE_FLOCK)
60 int lutil_lockf ( int fd ) {
65 int lutil_unlockf ( int fd ) {
72 int lutil_lockf ( int fd ) {
73 /* use F_LOCK instead of F_TLOCK, ie: block */
74 return lockf( fd, F_LOCK, 0 );
77 int lutil_unlockf ( int fd ) {
78 return lockf( fd, F_ULOCK, 0 );
83 int lutil_lockf ( int fd ) {
84 struct flock file_lock;
86 memset( &file_lock, '\0', sizeof( file_lock ) );
87 file_lock.l_type = F_WRLCK;
88 file_lock.l_whence = SEEK_SET;
89 file_lock.l_start = 0;
92 /* use F_SETLKW instead of F_SETLK, ie: block */
93 return( fcntl( fd, F_SETLKW, &file_lock ) );
96 int lutil_unlockf ( int fd ) {
97 struct flock file_lock;
99 memset( &file_lock, '\0', sizeof( file_lock ) );
100 file_lock.l_type = F_UNLCK;
101 file_lock.l_whence = SEEK_SET;
102 file_lock.l_start = 0;
105 return( fcntl ( fd, F_SETLKW, &file_lock ) );
110 int lutil_lockf ( int fd ) {
111 /* use LOCK_EX instead of LOCK_EX|LOCK_NB, ie: block */
112 return flock( fd, LOCK_EX );
115 int lutil_unlockf ( int fd ) {
116 return flock( fd, LOCK_UN );