1 /* 2 * Copyright (c) 1998, 1999 Sendmail, Inc. and its suppliers. 3 * All rights reserved. 4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. 5 * Copyright (c) 1988, 1993 6 * The Regents of the University of California. All rights reserved. 7 * 8 * By using this file, you agree to the terms and conditions set 9 * forth in the LICENSE file which can be found at the top level of 10 * the sendmail distribution. 11 * 12 */ 13 14 #ifndef lint 15 static char id[] = "@(#)$Id: lockfile.c,v 8.3 1999/08/31 15:38:27 ca Exp $"; 16 #endif /* ! lint */ 17 18 #include <sendmail.h> 19 20 /* 21 ** LOCKFILE -- lock a file using flock or (shudder) fcntl locking 22 ** 23 ** Parameters: 24 ** fd -- the file descriptor of the file. 25 ** filename -- the file name (for error messages). [unused] 26 ** ext -- the filename extension. [unused] 27 ** type -- type of the lock. Bits can be: 28 ** LOCK_EX -- exclusive lock. 29 ** LOCK_NB -- non-blocking. 30 ** 31 ** Returns: 32 ** TRUE if the lock was acquired. 33 ** FALSE otherwise. 34 */ 35 36 bool 37 lockfile(fd, filename, ext, type) 38 int fd; 39 char *filename; 40 char *ext; 41 int type; 42 { 43 #if !HASFLOCK 44 int action; 45 struct flock lfd; 46 extern int errno; 47 48 memset(&lfd, '\0', sizeof lfd); 49 if (bitset(LOCK_UN, type)) 50 lfd.l_type = F_UNLCK; 51 else if (bitset(LOCK_EX, type)) 52 lfd.l_type = F_WRLCK; 53 else 54 lfd.l_type = F_RDLCK; 55 if (bitset(LOCK_NB, type)) 56 action = F_SETLK; 57 else 58 action = F_SETLKW; 59 60 if (fcntl(fd, action, &lfd) >= 0) 61 return TRUE; 62 63 /* 64 ** On SunOS, if you are testing using -oQ/tmp/mqueue or 65 ** -oA/tmp/aliases or anything like that, and /tmp is mounted 66 ** as type "tmp" (that is, served from swap space), the 67 ** previous fcntl will fail with "Invalid argument" errors. 68 ** Since this is fairly common during testing, we will assume 69 ** that this indicates that the lock is successfully grabbed. 70 */ 71 72 if (errno == EINVAL) 73 return TRUE; 74 75 #else /* !HASFLOCK */ 76 77 if (flock(fd, type) >= 0) 78 return TRUE; 79 80 #endif /* !HASFLOCK */ 81 82 return FALSE; 83 } 84