aboutsummaryrefslogtreecommitdiff
path: root/toys/other/flock.c
blob: 5f0190a9e287021e33fecbd93ee968697c2e0138 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* flock.c - manage advisory file locks
 *
 * Copyright 2015 The Android Open Source Project

USE_FLOCK(NEWTOY(flock, "<1>1nsux[-sux]", TOYFLAG_USR|TOYFLAG_BIN))

config FLOCK
  bool "flock"
  default y
  help
    usage: flock [-sxun] fd

    Manage advisory file locks.

    -s	Shared lock.
    -x	Exclusive lock (default).
    -u	Unlock.
    -n	Non-blocking: fail rather than wait for the lock.
*/

#define FOR_flock
#include "toys.h"

#include <sys/file.h>

void flock_main(void)
{
  int fd = xstrtol(*toys.optargs, NULL, 10), op;

  if (toys.optflags & FLAG_u) op = LOCK_UN;
  else op = (toys.optflags & FLAG_s) ? LOCK_SH : LOCK_EX;

  if (toys.optflags & FLAG_n) op |= LOCK_NB;

  if (flock(fd, op)) {
    if ((op & LOCK_NB) && errno == EAGAIN) toys.exitval = 1;
    else perror_exit("flock");
  }
}