added python installer
[tridge/junkcode.git] / lock_upgrade.c
1 #define _FILE_OFFSET_BITS 64
2 #include <stdio.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <errno.h>
7 #include <signal.h>
8 #include <string.h>
9 #include <sys/types.h>
10 #include <sys/wait.h>
11
12 static int brlock(int fd, int type)
13 {
14         struct flock lock;
15
16         lock.l_type = type;
17         lock.l_whence = SEEK_SET;
18         lock.l_start = 0;
19         lock.l_len = 1;
20         lock.l_pid = 0;
21
22         if (fcntl(fd,F_SETLKW,&lock) != 0) {
23                 printf("\nFailed to get lock type=%d in %d - %s\n",
24                        type, (int)getpid(), strerror(errno));
25                 return -1;
26         }
27         return 0;
28 }
29
30 static int tlock_read(int fd)
31 {
32         if (brlock(fd, F_RDLCK) != 0) return -1;
33         sleep(2);
34         if (brlock(fd, F_UNLCK) != 0) return -1;
35         return 0;
36 }
37
38 static int tlock_write(int fd)
39 {
40         if (brlock(fd, F_WRLCK) != 0) return -1;
41         if (brlock(fd, F_UNLCK) != 0) return -1;
42         return 0;
43 }
44
45 static int tlock_transaction(int fd)
46 {
47         if (brlock(fd, F_RDLCK) != 0) return -1;
48         if (brlock(fd, F_WRLCK) != 0) return -1;
49         if (brlock(fd, F_UNLCK) != 0) return -1;
50         return 0;
51 }
52
53 int main(void) 
54 {
55         const char *fname = "upgradetest.dat";
56         int fd, i;
57         #define N 2
58         pid_t pids[N];
59
60         unlink(fname);
61         fd = open(fname, O_CREAT|O_RDWR|O_EXCL, 0600);
62
63         brlock(fd, F_RDLCK);
64
65         /* fork 2 children */
66         if ((pids[0]=fork()) == 0) {
67                 tlock_read(fd);
68                 exit(0);
69         }
70         if ((pids[0]=fork()) == 0) {
71                 tlock_write(fd);
72                 exit(0);
73         }
74
75         sleep(1);
76         brlock(fd, F_UNLCK);
77
78         tlock_transaction(fd);
79
80         close(fd);
81
82         for (i=0;i<N;i++) {
83                 waitpid(-1, NULL, 0);
84         }
85
86         exit(0);
87 }