Work locking mechanisms for concurrent updates/commit.
[idzebra-moved-to-github.git] / index / locksrv.c
1 /*
2  * Copyright (C) 1994-1995, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: locksrv.c,v $
7  * Revision 1.1  1995-12-07 17:38:47  adam
8  * Work locking mechanisms for concurrent updates/commit.
9  *
10  */
11 #include <stdio.h>
12 #include <assert.h>
13 #include <unistd.h>
14 #include <sys/file.h>
15 #include <fcntl.h>
16 #include <string.h>
17 #include <errno.h>
18
19 #include <alexutil.h>
20 #include "index.h"
21
22 static int server_lock_fd = -1;
23
24 int zebraServerLock (void)
25 {
26     char pathPrefix[1024];
27     char path[1024];
28     
29     zebraLockPrefix (pathPrefix);
30
31     assert (server_lock_fd == -1);
32     sprintf (path, "%szebrasrv.%ld", pathPrefix, (long) getpid());
33     if ((server_lock_fd = open (path, O_CREAT|O_RDWR|O_SYNC|O_EXCL, 0666))
34         == -1)
35     {
36         logf (LOG_WARN|LOG_ERRNO, "remove stale %s", path);
37         unlink (path);
38         if ((server_lock_fd = open (path, O_CREAT|O_RDWR|O_SYNC|O_EXCL, 0666))
39             == -1)
40         {
41             logf (LOG_FATAL|LOG_ERRNO, "create %s", path);
42             return -1;
43         }
44     }
45     flock (server_lock_fd, LOCK_EX);
46
47     return 0;
48 }
49
50 int zebraServerLockGetState (void)
51 {
52     char pathPrefix[1024];
53     char path[1024];
54     char buf[256];
55     int fd;
56     
57     zebraLockPrefix (pathPrefix);
58
59     sprintf (path, "%s%s", pathPrefix, FNAME_MAIN_LOCK);
60     fd = open (path, O_RDONLY);
61     if (fd == -1)
62         return 0;
63     if (read (fd, buf, 2) == 0)
64         return 0;
65     close (fd);
66     return *buf;
67 }
68
69 void zebraServerLockMsg (const char *str)
70 {
71     int l, r;
72
73     assert (server_lock_fd != -1);
74     lseek (server_lock_fd, 0L, SEEK_SET);
75     l = strlen(str);
76     r = write (server_lock_fd, str, l);
77     if (r != l)
78     {
79         logf (LOG_FATAL|LOG_ERRNO, "write server lock file");
80         exit (1);
81     }
82 }
83
84 void zebraServerUnlock (void)
85 {
86     char pathPrefix[1024];
87     char path[1024];
88     
89     assert (server_lock_fd != -1);
90     zebraLockPrefix (pathPrefix);
91     flock (server_lock_fd, LOCK_UN);
92     sprintf (path, "%szebrasrv.%ld", pathPrefix, (long) getpid());
93     unlink (path);
94 }
95