1 #include <errno.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 
lockf(int fd,int op,off_t size)5 int lockf(int fd, int op, off_t size) {
6     struct flock l = {
7         .l_type = F_WRLCK, .l_whence = SEEK_CUR, .l_len = size,
8     };
9     switch (op) {
10     case F_TEST:
11         l.l_type = F_RDLCK;
12         if (fcntl(fd, F_GETLK, &l) < 0)
13             return -1;
14         if (l.l_type == F_UNLCK || l.l_pid == getpid())
15             return 0;
16         errno = EACCES;
17         return -1;
18     case F_ULOCK:
19         l.l_type = F_UNLCK;
20     case F_TLOCK:
21         return fcntl(fd, F_SETLK, &l);
22     case F_LOCK:
23         return fcntl(fd, F_SETLKW, &l);
24     }
25     errno = EINVAL;
26     return -1;
27 }
28