lock -n is similiar to flock -n. If the lock was already taken,
fail with exit code = 1 and write error message to stderr.
example:
if ! lock -n /tmp/foo ; then
echo lock exits.
else
echo lock was free. But is locked now.
fi
> lock was free. But is locked now.
> lock exists.
Signed-off-by: Alexander Couzens <lynxis@fe80.eu>
SVN-Revision: 46836
lib-$(CONFIG_MICROCOM) += microcom.o
--- /dev/null
+++ b/miscutils/lock.c
lib-$(CONFIG_MICROCOM) += microcom.o
--- /dev/null
+++ b/miscutils/lock.c
+/*
+ * Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org>
+ *
+/*
+ * Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org>
+ *
+static int unlock = 0;
+static int shared = 0;
+static int waitonly = 0;
+static int unlock = 0;
+static int shared = 0;
+static int waitonly = 0;
++static int try_lock = 0;
+static int fd;
+static char *file;
+
+static int fd;
+static char *file;
+
+ " -s Use shared locking\n"
+ " -u Unlock\n"
+ " -w Wait for the lock to become free, don't acquire lock\n"
+ " -s Use shared locking\n"
+ " -u Unlock\n"
+ " -w Wait for the lock to become free, don't acquire lock\n"
++ " -n Don't wait for the lock to become free. Fail with exit code\n"
+ "\n", name);
+ exit(1);
+}
+ "\n", name);
+ exit(1);
+}
+static int do_lock(void)
+{
+ int pid;
+static int do_lock(void)
+{
+ int pid;
+ char pidstr[8];
+
+ if ((fd = open(file, O_RDWR | O_CREAT | O_EXCL, 0700)) < 0) {
+ char pidstr[8];
+
+ if ((fd = open(file, O_RDWR | O_CREAT | O_EXCL, 0700)) < 0) {
-+ if (flock(fd, (shared ? LOCK_SH : LOCK_EX)) < 0) {
++ flags = shared ? LOCK_SH : LOCK_EX;
++ flags |= try_lock ? LOCK_NB : 0;
++
++ if (flock(fd, flags) < 0) {
+ fprintf(stderr, "Can't lock %s\n", file);
+ return 1;
+ }
+ fprintf(stderr, "Can't lock %s\n", file);
+ return 1;
+ }
+ case 'u':
+ unlock = 1;
+ break;
+ case 'u':
+ unlock = 1;
+ break;
++ case 'n':
++ try_lock = 1;
++ break;