Import Upstream version 0.66.4
[hcoop/debian/courier-authlib.git] / libs / liblock / locktest.c
1 /*
2 ** Copyright 1998 - 2014 Double Precision, Inc. See COPYING for
3 ** distribution information.
4 */
5
6 #include "liblock.h"
7 #if USE_FCNTL
8 #include "lockfcntl.c"
9 #endif
10 #if USE_FLOCK
11 #include "lockflock.c"
12 #endif
13 #if USE_LOCKF
14 #include "locklockf.c"
15 #endif
16 #include <signal.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <stdio.h>
20
21 int main()
22 {
23 #define FILENAME "courier-imap.locktest.XXXXXXXXXX"
24 int fd[2];
25 pid_t p;
26 int s;
27 int f;
28
29 char *name;
30 const char *tmpdir;
31 if ((tmpdir = (char *)getenv("TMPDIR")) == NULL || !*tmpdir)
32 tmpdir = "/tmp";
33
34 if ((name=malloc(strlen(tmpdir)+sizeof(FILENAME)+1)) == NULL)
35 {
36 perror("get filename");
37 exit(1);
38 }
39
40 (void)sprintf(name, "%s/%s", tmpdir, FILENAME);
41
42 signal(SIGCHLD, SIG_DFL);
43 if (pipe(fd))
44 {
45 perror("pipe");
46 return (1);
47 }
48
49 if ((f=mkstemp(name)) < 0)
50 {
51 perror("open");
52 exit(1);
53 }
54
55 if ((p=fork()) == (pid_t)-1)
56 {
57 perror("fork");
58 return (1);
59 }
60
61 if (p == 0)
62 {
63 char c;
64
65 close(fd[1]);
66 read(fd[0], &c, 1);
67 close(fd[0]);
68
69 if ((f=open(name, O_RDWR)) < 0)
70 {
71 perror("open");
72 exit(1);
73 }
74 alarm(5);
75
76 if (ll_lockfd(f, ll_writelock, 0, 0))
77 {
78 close(f);
79 unlink(name);
80 exit(0);
81 }
82 close(f);
83 exit(1);
84 }
85
86 if (ll_lockfd(f, ll_writelock, 0, 0))
87 {
88 perror("lock");
89 close(f);
90 unlink(name);
91 exit(1);
92 }
93 close(fd[1]);
94 close(fd[0]);
95 while (wait(&s) != p)
96 ;
97 if (s == 0)
98 exit(0);
99 exit(1);
100 }