1 /* $Id: flock.c,v 1.5 2006-03-25 10:06:55 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 = 0 /* YLOG_LOG|YLOG_FLUSH */;
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);
101 yaz_log(log_level, "zebra_lock_create fd=%d p=%p fname=%s", h->fd, h, h->fname);
105 void zebra_lock_destroy (ZebraLockHandle h)
109 yaz_log(log_level, "zebra_lock_destroy fd=%d p=%p fname=%s", h->fd, h, h->fname);
117 static int unixLock (int fd, int type, int cmd)
121 area.l_whence = SEEK_SET;
122 area.l_len = area.l_start = 0L;
123 return fcntl (fd, cmd, &area);
127 int zebra_lock_w (ZebraLockHandle h)
130 yaz_log(log_level, "zebra_lock_w fd=%d p=%p fname=%s", h->fd, h, h->fname);
132 while ((r = _locking (h->fd, _LK_LOCK, 1)))
135 r = unixLock (h->fd, F_WRLCK, F_SETLKW);
137 yaz_log(log_level, "zebra_lock_w fd=%d p=%p fname=%s OK", h->fd, h, h->fname);
141 int zebra_lock_r (ZebraLockHandle h)
144 yaz_log(log_level, "zebra_lock_r fd=%d p=%p fname=%s", h->fd, h, h->fname);
146 while ((r = _locking (h->fd, _LK_LOCK, 1)))
149 r = unixLock (h->fd, F_RDLCK, F_SETLKW);
151 yaz_log(log_level, "zebra_lock_r fd=%d p=%p fname=%s OK", h->fd, h, h->fname);
155 int zebra_unlock (ZebraLockHandle h)
157 yaz_log(log_level, "zebra_unlock fd=%d p=%p fname=%s", h->fd, h, h->fname);
159 return _locking (h->fd, _LK_UNLCK, 1);
161 return unixLock (h->fd, F_UNLCK, F_SETLKW);