/*- * Copyright (c) 1999 Ian Freislich * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $Id: lockfile.c,v 1.3 2002/06/19 09:21:44 ianf Exp $ */ #include #include #include int openlock(const char *path, int flags, ...) { mode_t mode; va_list ap; int fd, result; #ifndef HAS_FLOCK struct flock fl; #endif if (flags & O_CREAT) { va_start(ap, flags); mode = (mode_t)va_arg(ap, int); va_end(ap); fd = open(path, flags & ~O_NONBLOCK, mode); } else fd = open(path, flags & ~O_NONBLOCK); if (fd < 0) return(fd); #ifdef HAS_FLOCK result = flock(fd, LOCK_EX|(flags & O_NONBLOCK ? LOCK_NB : NULL)); #else fl.l_start = 0; fl.l_len = 0; fl.l_type = (flags & O_ACCMODE) == O_RDONLY ? F_RDLCK : fl.l_type; fl.l_type = (flags & O_ACCMODE) == O_WRONLY ? F_WRLCK : fl.l_type; fl.l_type = (flags & O_ACCMODE) == O_RDWR ? F_WRLCK : fl.l_type; fl.l_whence = SEEK_SET; result = fcntl(fd, (flags & O_NONBLOCK) ? F_SETLK : F_SETLKW, &fl); #endif if (result < 0) { close(fd); return(-1); } return(fd); }