Fix for libidzebra-2.0-dev
[idzebra-moved-to-github.git] / util / tstlockscope.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1994-2011 Index Data
3
4 Zebra is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 /** \file tstlockscope.c
21     \brief tests scope of fcntl locks.. Either "process"  or "thread"
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27 #include <assert.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <yaz/log.h>
32 #include <yaz/test.h>
33 #include <fcntl.h>
34 #if YAZ_POSIX_THREADS
35 #include <pthread.h>
36 #endif
37
38 int fd;
39
40 const char *scope = "unknown";
41
42 static int file_lock(int fd, int type, int cmd)
43 {
44     struct flock area;
45     area.l_type = type;
46     area.l_whence = SEEK_SET;
47     area.l_len = area.l_start = 0L;
48
49     return fcntl(fd, cmd, &area);
50 }
51
52 void *run_func(void *arg)
53 {
54     if (file_lock(fd, F_WRLCK, F_SETLK) == -1)
55         scope = "thread";
56     else
57         scope = "process";
58     return 0;
59 }
60
61 void tst(void)
62 {
63     pthread_t child_thread;
64     int r;
65     fd = open("my.LCK", (O_CREAT|O_RDWR), 0666);
66
67     YAZ_CHECK(fd != -1);
68     if (fd == -1)
69     {
70         yaz_log(YLOG_FATAL|YLOG_ERRNO, "open");
71         return;
72     }
73
74     r = file_lock(fd, F_WRLCK, F_SETLKW);
75     YAZ_CHECK(r != -1);
76     if (r == -1)
77     {
78         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcnt");
79         return;
80     }
81
82 #if YAZ_POSIX_THREADS
83     pthread_create(&child_thread, 0 /* attr */, run_func, 0);
84     pthread_join(child_thread, 0);
85 #endif
86     yaz_log(YLOG_LOG, "fcntl lock scope: %s", scope);
87 }
88
89 int main(int argc, char **argv)
90 {
91     YAZ_CHECK_INIT(argc, argv);
92     YAZ_CHECK_LOG();
93     tst();
94     YAZ_CHECK_TERM;
95     return 0;
96 }
97
98 /*
99  * Local variables:
100  * c-basic-offset: 4
101  * c-file-style: "Stroustrup"
102  * indent-tabs-mode: nil
103  * End:
104  * vim: shiftwidth=4 tabstop=8 expandtab
105  */
106