first pass at updating head branch to be to be the same as the SAMBA_2_0 branch
[kai/samba-autobuild/.git] / source3 / tests / fcntl_lock.c
1 /* test whether fcntl locking works on this system */
2
3 #if defined(HAVE_UNISTD_H)
4 #include <unistd.h>
5 #endif
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/types.h>
10
11 #ifdef HAVE_FCNTL_H
12 #include <fcntl.h>
13 #endif
14
15 #ifdef HAVE_SYS_FCNTL_H
16 #include <sys/fcntl.h>
17 #endif
18
19 #include <errno.h>
20
21 static int sys_waitpid(pid_t pid,int *status,int options)
22 {
23 #ifdef HAVE_WAITPID
24   return waitpid(pid,status,options);
25 #else /* USE_WAITPID */
26   return wait4(pid, status, options, NULL);
27 #endif /* USE_WAITPID */
28 }
29
30 #define DATA "conftest.fcntl"
31
32 #ifndef SEEK_SET
33 #define SEEK_SET 0
34 #endif
35
36 /* lock a byte range in a open file */
37 int main(int argc, char *argv[])
38 {
39         struct flock lock;
40         int fd, ret, status=1;
41         pid_t pid;
42
43         if (!(pid=fork())) {
44                 sleep(2);
45                 fd = open(DATA, O_RDONLY);
46
47                 if (fd == -1) exit(1);
48
49                 lock.l_type = F_WRLCK;
50                 lock.l_whence = SEEK_SET;
51                 lock.l_start = 0;
52                 lock.l_len = 4;
53                 lock.l_pid = getpid();
54                 
55                 lock.l_type = F_WRLCK;
56                 
57                 /* check if a lock applies */
58                 ret = fcntl(fd,F_GETLK,&lock);
59
60                 if ((ret == -1) ||
61                     (lock.l_type == F_UNLCK)) {
62                         exit(1);
63                 } else {
64                         exit(0);
65                 }
66         }
67
68         fd = open(DATA, O_RDWR|O_CREAT|O_TRUNC, 0600);
69
70         lock.l_type = F_WRLCK;
71         lock.l_whence = SEEK_SET;
72         lock.l_start = 0;
73         lock.l_len = 4;
74         lock.l_pid = getpid();
75
76         /* set a 4 byte write lock */
77         fcntl(fd,F_SETLK,&lock);
78
79         sys_waitpid(pid, &status, 0);
80
81         unlink(DATA);
82
83 #if defined(WIFEXITED) && defined(WEXITSTATUS)
84     if(WIFEXITED(status)) {
85         status = WEXITSTATUS(status);
86     } else {
87         status = 1;
88     }
89 #else /* defined(WIFEXITED) && defined(WEXITSTATUS) */
90         status = (status == 0) ? 0 : 1;
91 #endif /* defined(WIFEXITED) && defined(WEXITSTATUS) */
92
93         exit(status);
94 }