2 * Copyright (C) 1994-2002, Index Data
4 * Sebastian Hammer, Adam Dickmeiss
6 * $Id: lockutil.c,v 1.14 2002-03-21 10:25:42 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 int dlen = dir ? strlen(dir) : 0;
65 char *fname = zebra_mk_fname(dir, name);
66 ZebraLockHandle h = (ZebraLockHandle) xmalloc (sizeof(*h));
68 h->excl_flag = excl_flag;
74 h->fd = open (name, O_BINARY|O_RDONLY);
76 h->fd = open (fname, ((h->excl_flag > 1) ? O_EXCL : 0)|
77 (O_BINARY|O_CREAT|O_RDWR), 0666);
79 h->fd= open (fname, ((h->excl_flag > 1) ? O_EXCL : 0)|
80 (O_BINARY|O_CREAT|O_RDWR|O_SYNC), 0666);
84 if (h->excl_flag <= 1)
85 logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
93 void zebra_lock_destroy (ZebraLockHandle h)
102 void zebra_lock_prefix (Res res, char *path)
104 char *lock_dir = res_get_def (res, "lockDir", "");
106 strcpy (path, lock_dir);
107 if (*path && path[strlen(path)-1] != '/')
112 static int unixLock (int fd, int type, int cmd)
116 area.l_whence = SEEK_SET;
117 area.l_len = area.l_start = 0L;
118 return fcntl (fd, cmd, &area);
122 int zebra_lock_w (ZebraLockHandle h)
125 return _locking (h->fd, _LK_LOCK, 1);
127 return unixLock (h->fd, F_WRLCK, F_SETLKW);
131 int zebra_lock_r (ZebraLockHandle h)
134 return _locking (h->fd, _LK_LOCK, 1);
136 return unixLock (h->fd, F_RDLCK, F_SETLKW);
140 int zebra_lock (ZebraLockHandle h)
143 return _locking (h->fd, _LK_LOCK, 1);
145 return unixLock (h->fd, h->excl_flag ? F_WRLCK : F_RDLCK, F_SETLKW);
149 int zebra_lock_nb (ZebraLockHandle h)
152 return _locking (h->fd, _LK_NBLCK, 1);
154 return unixLock (h->fd, h->excl_flag ? F_WRLCK : F_RDLCK, F_SETLK);
158 int zebra_unlock (ZebraLockHandle h)
161 return _locking (h->fd, _LK_UNLCK, 1);
163 return unixLock (h->fd, F_UNLCK, F_SETLKW);
167 int zebra_lock_fd (ZebraLockHandle h)