1 /* $Id: flock.c,v 1.3 2006-03-23 20:40:31 adam Exp $
2 Copyright (C) 1995-2005
5 This file is part of the Zebra server.
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra. If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
29 #include <sys/types.h>
32 #include <sys/locking.h>
38 #include <idzebra/flock.h>
39 #include <yaz/xmalloc.h>
42 struct zebra_lock_info {
47 static int log_level = YLOG_LOG;
49 char *zebra_mk_fname (const char *dir, const char *name)
51 int dlen = dir ? strlen(dir) : 0;
52 char *fname = xmalloc (dlen + strlen(name) + 3);
57 int last_one = dir[dlen-1];
59 if (!strchr ("/\\:", last_one))
60 sprintf (fname, "%s\\%s", dir, name);
62 sprintf (fname, "%s%s", dir, name);
65 sprintf (fname, "%s", name);
69 int last_one = dir[dlen-1];
71 if (!strchr ("/", last_one))
72 sprintf (fname, "%s/%s", dir, name);
74 sprintf (fname, "%s%s", dir, name);
77 sprintf (fname, "%s", name);
82 ZebraLockHandle zebra_lock_create (const char *dir, const char *name)
84 char *fname = zebra_mk_fname(dir, name);
85 ZebraLockHandle h = (ZebraLockHandle) xmalloc (sizeof(*h));
89 h->fd = open (name, O_BINARY|O_RDONLY);
91 h->fd = open (fname, (O_BINARY|O_CREAT|O_RDWR), 0666);
93 h->fd= open (fname, (O_BINARY|O_CREAT|O_RDWR), 0666);
104 void zebra_lock_destroy (ZebraLockHandle h)
115 static int unixLock (int fd, int type, int cmd)
119 area.l_whence = SEEK_SET;
120 area.l_len = area.l_start = 0L;
121 return fcntl (fd, cmd, &area);
125 int zebra_lock_w (ZebraLockHandle h)
127 yaz_log(log_level, "zebra_lock_w p=%p fname=%s", h, h->fname);
129 return _locking (h->fd, _LK_LOCK, 1);
131 return unixLock (h->fd, F_WRLCK, F_SETLKW);
135 int zebra_lock_r (ZebraLockHandle h)
137 yaz_log(log_level, "zebra_lock_r p=%p fname=%s", h, h->fname);
139 return _locking (h->fd, _LK_LOCK, 1);
141 return unixLock (h->fd, F_RDLCK, F_SETLKW);
145 int zebra_unlock (ZebraLockHandle h)
147 yaz_log(log_level, "zebra_unlock fd=%d p=%p fname=%s", h->fd, h, h->fname);
149 return _locking (h->fd, _LK_UNLCK, 1);
151 return unixLock (h->fd, F_UNLCK, F_SETLKW);