2 * Copyright (C) 1994-2002, Index Data
4 * Sebastian Hammer, Adam Dickmeiss
6 * $Id: lockutil.c,v 1.15 2002-04-04 14:14:13 adam Exp $
13 #include <sys/types.h>
16 #include <sys/locking.h>
23 struct zebra_lock_info {
28 char *zebra_mk_fname (const char *dir, const char *name)
30 int dlen = dir ? strlen(dir) : 0;
31 char *fname = xmalloc (dlen + strlen(name) + 3);
36 int last_one = dir[dlen-1];
38 if (!strchr ("/\\:", last_one))
39 sprintf (fname, "%s\\%s", dir, name);
41 sprintf (fname, "%s%s", dir, name);
44 sprintf (fname, "%s", name);
48 int last_one = dir[dlen-1];
50 if (!strchr ("/", last_one))
51 sprintf (fname, "%s/%s", dir, name);
53 sprintf (fname, "%s%s", dir, name);
56 sprintf (fname, "%s", name);
61 ZebraLockHandle zebra_lock_create (const char *dir,
62 const char *name, int excl_flag)
64 char *fname = zebra_mk_fname(dir, name);
65 ZebraLockHandle h = (ZebraLockHandle) xmalloc (sizeof(*h));
67 h->excl_flag = excl_flag;
73 h->fd = open (name, O_BINARY|O_RDONLY);
75 h->fd = open (fname, ((h->excl_flag > 1) ? O_EXCL : 0)|
76 (O_BINARY|O_CREAT|O_RDWR), 0666);
78 h->fd= open (fname, ((h->excl_flag > 1) ? O_EXCL : 0)|
79 (O_BINARY|O_CREAT|O_RDWR|O_SYNC), 0666);
83 if (h->excl_flag <= 1)
84 logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
92 void zebra_lock_destroy (ZebraLockHandle h)
101 void zebra_lock_prefix (Res res, char *path)
103 char *lock_dir = res_get_def (res, "lockDir", "");
105 strcpy (path, lock_dir);
106 if (*path && path[strlen(path)-1] != '/')
111 static int unixLock (int fd, int type, int cmd)
115 area.l_whence = SEEK_SET;
116 area.l_len = area.l_start = 0L;
117 return fcntl (fd, cmd, &area);
121 int zebra_lock_w (ZebraLockHandle h)
124 return _locking (h->fd, _LK_LOCK, 1);
126 return unixLock (h->fd, F_WRLCK, F_SETLKW);
130 int zebra_lock_r (ZebraLockHandle h)
133 return _locking (h->fd, _LK_LOCK, 1);
135 return unixLock (h->fd, F_RDLCK, F_SETLKW);
139 int zebra_lock (ZebraLockHandle h)
142 return _locking (h->fd, _LK_LOCK, 1);
144 return unixLock (h->fd, h->excl_flag ? F_WRLCK : F_RDLCK, F_SETLKW);
148 int zebra_lock_nb (ZebraLockHandle h)
151 return _locking (h->fd, _LK_NBLCK, 1);
153 return unixLock (h->fd, h->excl_flag ? F_WRLCK : F_RDLCK, F_SETLK);
157 int zebra_unlock (ZebraLockHandle h)
160 return _locking (h->fd, _LK_UNLCK, 1);
162 return unixLock (h->fd, F_UNLCK, F_SETLKW);
166 int zebra_lock_fd (ZebraLockHandle h)