1 /* lock.c - Implement basic file locking for GDBM. */
3 /* This file is part of GDBM, the GNU data base manager.
4 Copyright (C) 2008, 2011 Free Software Foundation, Inc.
6 GDBM is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
11 GDBM is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GDBM. If not, see <http://www.gnu.org/licenses/>. */
19 /* Include system configuration before all else. */
44 #if defined(F_SETLK) && defined(F_RDLCK) && defined(F_WRLCK)
45 # define HAVE_FCNTL_LOCK 1
47 # define HAVE_FCNTL_LOCK 0
52 gdbm_locked (GDBM_FILE dbf)
54 return (dbf->lock_type != LOCKING_NONE);
59 _gdbm_unlock_file (GDBM_FILE dbf)
65 switch (dbf->lock_type)
69 flock (dbf->desc, LOCK_UN);
75 lockf (dbf->desc, F_ULOCK, (off_t)0L);
82 fl.l_whence = SEEK_SET;
83 fl.l_start = fl.l_len = (off_t)0L;
84 fcntl (dbf->desc, F_SETLK, &fl);
92 dbf->lock_type = LOCKING_NONE;
95 /* Try each supported locking mechanism. */
97 _gdbm_lock_file (GDBM_FILE dbf)
105 if (dbf->read_write == GDBM_READER)
106 lock_val = flock (dbf->desc, LOCK_SH + LOCK_NB);
108 lock_val = flock (dbf->desc, LOCK_EX + LOCK_NB);
110 if ((lock_val == -1) && (errno == EWOULDBLOCK))
112 dbf->lock_type = LOCKING_NONE;
115 else if (lock_val != -1)
117 dbf->lock_type = LOCKING_FLOCK;
123 /* Mask doesn't matter for lockf. */
124 lock_val = lockf (dbf->desc, F_LOCK, (off_t)0L);
125 if ((lock_val == -1) && (errno == EDEADLK))
127 dbf->lock_type = LOCKING_NONE;
130 else if (lock_val != -1)
132 dbf->lock_type = LOCKING_LOCKF;
138 /* If we're still here, try fcntl. */
139 if (dbf->read_write == GDBM_READER)
143 fl.l_whence = SEEK_SET;
144 fl.l_start = fl.l_len = (off_t)0L;
145 lock_val = fcntl (dbf->desc, F_SETLK, &fl);
148 dbf->lock_type = LOCKING_FCNTL;
152 dbf->lock_type = LOCKING_NONE;