depmaker
[tridge/junkcode.git] / lock_inherit.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <fcntl.h>
7 #include <errno.h>
8 #include <sys/mman.h>
9 #include <sys/stat.h>
10
11
12 #define LOCK_SET 1
13 #define LOCK_CLEAR 0
14
15 /* a byte range locking function - return 0 on success
16    this functions locks/unlocks 1 byte at the specified offset */
17 static int tdb_brlock(int fd, off_t offset, int set, int rw_type, int lck_type)
18 {
19         struct flock fl;
20
21         fl.l_type = set==LOCK_SET?rw_type:F_UNLCK;
22         fl.l_whence = SEEK_SET;
23         fl.l_start = offset;
24         fl.l_len = 1;
25         fl.l_pid = 0;
26
27         if (fcntl(fd, lck_type, &fl) != 0) {
28                 return -1;
29         }
30         return 0;
31 }
32
33
34 main()
35 {
36         int fd = open("lcktest.dat", O_RDWR|O_CREAT|O_TRUNC, 0600);
37
38         tdb_brlock(fd, 0, LOCK_SET, F_RDLCK, F_SETLKW);
39
40         if (fork()) {
41                 /* parent */
42                 close(fd);
43
44                 fd = open("lcktest.dat", O_RDWR, 0600);
45
46                 if (tdb_brlock(fd, 0, LOCK_SET, F_WRLCK, F_SETLKW) == 0) {
47                         printf("child doesn't hold lock\n");
48                 } else {
49                         printf("child does hold lock\n");
50                 }
51         } 
52         sleep(2);
53 }