10f66f451Sopenharmony_ci/* flock.c - manage advisory file locks
20f66f451Sopenharmony_ci *
30f66f451Sopenharmony_ci * Copyright 2015 The Android Open Source Project
40f66f451Sopenharmony_ci
50f66f451Sopenharmony_ciUSE_FLOCK(NEWTOY(flock, "<1>1nsux[-sux]", TOYFLAG_USR|TOYFLAG_BIN))
60f66f451Sopenharmony_ci
70f66f451Sopenharmony_ciconfig FLOCK
80f66f451Sopenharmony_ci  bool "flock"
90f66f451Sopenharmony_ci  default y
100f66f451Sopenharmony_ci  help
110f66f451Sopenharmony_ci    usage: flock [-sxun] fd
120f66f451Sopenharmony_ci
130f66f451Sopenharmony_ci    Manage advisory file locks.
140f66f451Sopenharmony_ci
150f66f451Sopenharmony_ci    -s	Shared lock
160f66f451Sopenharmony_ci    -x	Exclusive lock (default)
170f66f451Sopenharmony_ci    -u	Unlock
180f66f451Sopenharmony_ci    -n	Non-blocking: fail rather than wait for the lock
190f66f451Sopenharmony_ci*/
200f66f451Sopenharmony_ci
210f66f451Sopenharmony_ci#define FOR_flock
220f66f451Sopenharmony_ci#include "toys.h"
230f66f451Sopenharmony_ci
240f66f451Sopenharmony_ci#include <sys/file.h>
250f66f451Sopenharmony_ci
260f66f451Sopenharmony_civoid flock_main(void)
270f66f451Sopenharmony_ci{
280f66f451Sopenharmony_ci  int fd = xstrtol(*toys.optargs, NULL, 10), op;
290f66f451Sopenharmony_ci
300f66f451Sopenharmony_ci  if (toys.optflags & FLAG_u) op = LOCK_UN;
310f66f451Sopenharmony_ci  else op = (toys.optflags & FLAG_s) ? LOCK_SH : LOCK_EX;
320f66f451Sopenharmony_ci
330f66f451Sopenharmony_ci  if (toys.optflags & FLAG_n) op |= LOCK_NB;
340f66f451Sopenharmony_ci
350f66f451Sopenharmony_ci  if (flock(fd, op)) {
360f66f451Sopenharmony_ci    if ((op & LOCK_NB) && errno == EAGAIN) toys.exitval = 1;
370f66f451Sopenharmony_ci    else perror_exit("flock");
380f66f451Sopenharmony_ci  }
390f66f451Sopenharmony_ci}
40