• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* flock.c - manage advisory file locks
2  *
3  * Copyright 2015 The Android Open Source Project
4 
5 USE_FLOCK(NEWTOY(flock, "<1>1nsux[-sux]", TOYFLAG_USR|TOYFLAG_BIN))
6 
7 config FLOCK
8   bool "flock"
9   default y
10   help
11     usage: flock [-sxun] fd
12 
13     Manage advisory file locks.
14 
15     -s	Shared lock.
16     -x	Exclusive lock (default).
17     -u	Unlock.
18     -n	Non-blocking: fail rather than wait for the lock.
19 */
20 
21 #define FOR_flock
22 #include "toys.h"
23 
24 #include <sys/file.h>
25 
flock_main(void)26 void flock_main(void)
27 {
28   int fd = xstrtol(*toys.optargs, NULL, 10), op;
29 
30   if (toys.optflags & FLAG_u) op = LOCK_UN;
31   else op = (toys.optflags & FLAG_s) ? LOCK_SH : LOCK_EX;
32 
33   if (toys.optflags & FLAG_n) op |= LOCK_NB;
34 
35   if (flock(fd, op)) {
36     if ((op & LOCK_NB) && errno == EAGAIN) toys.exitval = 1;
37     else perror_exit("flock");
38   }
39 }
40