1 /* $Id: flock.c,v 1.1 2006-03-23 09:15:25 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>
41 struct zebra_lock_info {
45 char *zebra_mk_fname (const char *dir, const char *name)
47 int dlen = dir ? strlen(dir) : 0;
48 char *fname = xmalloc (dlen + strlen(name) + 3);
53 int last_one = dir[dlen-1];
55 if (!strchr ("/\\:", last_one))
56 sprintf (fname, "%s\\%s", dir, name);
58 sprintf (fname, "%s%s", dir, name);
61 sprintf (fname, "%s", name);
65 int last_one = dir[dlen-1];
67 if (!strchr ("/", last_one))
68 sprintf (fname, "%s/%s", dir, name);
70 sprintf (fname, "%s%s", dir, name);
73 sprintf (fname, "%s", name);
78 ZebraLockHandle zebra_lock_create (const char *dir, const char *name)
80 char *fname = zebra_mk_fname(dir, name);
81 ZebraLockHandle h = (ZebraLockHandle) xmalloc (sizeof(*h));
85 h->fd = open (name, O_BINARY|O_RDONLY);
87 h->fd = open (fname, (O_BINARY|O_CREAT|O_RDWR), 0666);
89 h->fd= open (fname, (O_BINARY|O_CREAT|O_RDWR), 0666);
100 void zebra_lock_destroy (ZebraLockHandle h)
110 static int unixLock (int fd, int type, int cmd)
114 area.l_whence = SEEK_SET;
115 area.l_len = area.l_start = 0L;
116 return fcntl (fd, cmd, &area);
120 int zebra_lock_w (ZebraLockHandle h)
123 return _locking (h->fd, _LK_LOCK, 1);
125 return unixLock (h->fd, F_WRLCK, F_SETLKW);
129 int zebra_lock_r (ZebraLockHandle h)
132 return _locking (h->fd, _LK_LOCK, 1);
134 return unixLock (h->fd, F_RDLCK, F_SETLKW);
138 int zebra_unlock (ZebraLockHandle h)
141 return _locking (h->fd, _LK_UNLCK, 1);
143 return unixLock (h->fd, F_UNLCK, F_SETLKW);