1N/A/*
1N/A * Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.
1N/A * All rights reserved.
1N/A * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
1N/A * Copyright (c) 1988, 1993
1N/A * The Regents of the University of California. All rights reserved.
1N/A *
1N/A * By using this file, you agree to the terms and conditions set
1N/A * forth in the LICENSE file which can be found at the top level of
1N/A * the sendmail distribution.
1N/A *
1N/A */
1N/A
1N/A#pragma ident "%Z%%M% %I% %E% SMI"
1N/A
1N/A#include <sendmail.h>
1N/A
1N/ASM_RCSID("@(#)$Id: lockfile.c,v 8.21 2003/11/10 22:57:38 ca Exp $")
1N/A
1N/A
1N/A/*
1N/A** LOCKFILE -- lock a file using flock or (shudder) fcntl locking
1N/A**
1N/A** Parameters:
1N/A** fd -- the file descriptor of the file.
1N/A** filename -- the file name (for error messages). [unused]
1N/A** ext -- the filename extension. [unused]
1N/A** type -- type of the lock. Bits can be:
1N/A** LOCK_EX -- exclusive lock.
1N/A** LOCK_NB -- non-blocking.
1N/A** LOCK_UN -- unlock.
1N/A**
1N/A** Returns:
1N/A** true if the lock was acquired.
1N/A** false otherwise.
1N/A*/
1N/A
1N/Abool
1N/Alockfile(fd, filename, ext, type)
1N/A int fd;
1N/A char *filename;
1N/A char *ext;
1N/A int type;
1N/A{
1N/A#if !HASFLOCK
1N/A int action;
1N/A struct flock lfd;
1N/A
1N/A memset(&lfd, '\0', sizeof lfd);
1N/A if (bitset(LOCK_UN, type))
1N/A lfd.l_type = F_UNLCK;
1N/A else if (bitset(LOCK_EX, type))
1N/A lfd.l_type = F_WRLCK;
1N/A else
1N/A lfd.l_type = F_RDLCK;
1N/A if (bitset(LOCK_NB, type))
1N/A action = F_SETLK;
1N/A else
1N/A action = F_SETLKW;
1N/A
1N/A if (fcntl(fd, action, &lfd) >= 0)
1N/A return true;
1N/A
1N/A /*
1N/A ** On SunOS, if you are testing using -oQ/tmp/mqueue or
1N/A ** -oA/tmp/aliases or anything like that, and /tmp is mounted
1N/A ** as type "tmp" (that is, served from swap space), the
1N/A ** previous fcntl will fail with "Invalid argument" errors.
1N/A ** Since this is fairly common during testing, we will assume
1N/A ** that this indicates that the lock is successfully grabbed.
1N/A */
1N/A
1N/A if (errno == EINVAL)
1N/A return true;
1N/A
1N/A#else /* !HASFLOCK */
1N/A
1N/A if (flock(fd, type) >= 0)
1N/A return true;
1N/A
1N/A#endif /* !HASFLOCK */
1N/A
1N/A return false;
1N/A}