1 int main(int argc, char *argv[])
3 int type = F_UNLCK; /* lock type: default to unlock (invalid) */
4 off_t start = 0; /* start of the locked region: default to 0 */
5 off_t len = 0; /* length of the locked region: default to 0 */
6 int fd, res, i; /* internal variables */
7 int bsd = 0; /* semantic type: default to POSIX */
8 int cmd = F_SETLK; /* lock command: default to non-blocking */
9 struct flock lock; /* file lock structure */
11 if ((argc - optind) != 1) { /* There must be remaing parameters */
12 printf("Wrong number of arguments %d\n", argc - optind);
15 if (type == F_UNLCK) { /* There must be a -w or -r option set */
16 printf("You should set a read or a write lock\n");
19 fd = open(argv[optind], O_RDWR); /* open the file to be locked */
20 if (fd < 0) { /* on error exit */
21 perror("Wrong filename");
25 if (bsd) { /* if BSD locking */
26 /* rewrite cmd for suitables flock operation values */
27 if (cmd == F_SETLKW) { /* if no-blocking */
28 cmd = LOCK_NB; /* set the value for flock operation */
30 cmd = 0; /* default is null */
32 if (type == F_RDLCK) cmd |= LOCK_SH; /* set for shared lock */
33 if (type == F_WRLCK) cmd |= LOCK_EX; /* set for exclusive lock */
34 res = flock(fd, cmd); /* esecute lock */
35 } else { /* if POSIX locking */
36 /* setting flock structure */
37 lock.l_type = type; /* set type: read or write */
38 lock.l_whence = SEEK_SET; /* start from the beginning of the file */
39 lock.l_start = start; /* set the start of the locked region */
40 lock.l_len = len; /* set the length of the locked region */
41 res = fcntl(fd, cmd, &lock); /* do lock */
43 /* check lock results */
44 if (res) { /* on error exit */
45 perror("Failed lock");
47 } else { /* else write message */
48 printf("Lock acquired\n");
50 pause(); /* stop the process, use a signal to exit */