Whamcloud - gitweb
b=11564
[fs/lustre-release.git] / lustre / tests / flock_test.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <sys/file.h>
10 #include <sys/wait.h>
11
12 void chd_lock_unlock(int);
13 char fname[1024];
14
15 int main(int argc, char **argv)
16 {
17     pid_t pid;
18     int cfd, fd, rc;
19
20     if (argc != 2) {
21         fprintf(stderr, "\nUSAGE: flock_test filepath\n");
22         exit(2);
23     }
24     strncpy(fname, argv[1], 1023);
25     fname[1023] ='\0';
26     fd = open(fname, O_RDWR|O_CREAT, (mode_t)0666);
27     if (fd == -1) {
28         fprintf(stderr, "flock_test: failed to open %s : ", fname);
29         perror("");
30         exit(1);
31     }
32     if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
33         fprintf(stderr, "flock_test: parent attempt to lock %s failed : ", \
34             fname);
35         perror("");
36         exit(1);
37     }
38
39     pid = fork();
40     if (pid == -1) {
41         fprintf(stderr, "flock_test: fork failed : ");
42         perror("");
43         exit(1);
44     }
45
46     if (pid == 0) {
47         pid = getpid();
48         sleep(2);
49         if ((cfd = open(fname, O_RDWR)) == -1) {
50             fprintf(stderr, "flock_test child (%d) cannot open %s: ", \
51                 pid, fname);
52             perror("");
53             exit(1);
54         }
55         if(flock(cfd, LOCK_EX | LOCK_NB) != -1) {
56             fprintf(stderr, "flock_test child (%d): %s not yet locked  : ", \
57                 pid, fname);
58             exit(1);
59         }
60         if(flock(fd, LOCK_UN) == -1) {
61             fprintf(stderr, "flock_test child (%d): cannot unlock %s: ", \
62                 pid, fname);
63             perror("");
64             exit(1);
65         }
66         if(flock(cfd, LOCK_EX | LOCK_NB) == -1 ) {
67             fprintf(stderr, \
68                 "flock_test: child (%d) cannot re-lock %s after unlocking : ", \
69                 pid, fname);
70             perror("");
71             exit(1);
72         }
73         close(cfd);
74         exit(0);
75     }
76
77     waitpid(pid, &rc, 0);
78     close(fd);
79     unlink(fname);
80     if (WIFEXITED(rc) && WEXITSTATUS(rc) != 0) {
81         fprintf(stderr, "flock_test: child (%d) exit code = %d\n", \
82             pid, WEXITSTATUS(rc));
83         exit(1);
84     }
85     exit(0);
86 }