Skip to content
Snippets Groups Projects
Commit 3670f412 authored by Felix Fietkau's avatar Felix Fietkau
Browse files

busybox: lock: implement -n "Fail rather than wait"


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: default avatarAlexander Couzens <lynxis@fe80.eu>

SVN-Revision: 46836
parent 5fcafa31
No related branches found
No related tags found
No related merge requests found
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
lib-$(CONFIG_MICROCOM) += microcom.o lib-$(CONFIG_MICROCOM) += microcom.o
--- /dev/null --- /dev/null
+++ b/miscutils/lock.c +++ b/miscutils/lock.c
@@ -0,0 +1,135 @@ @@ -0,0 +1,144 @@
+/* +/*
+ * Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org> + * Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org>
+ * + *
...@@ -56,6 +56,7 @@ ...@@ -56,6 +56,7 @@
+static int unlock = 0; +static int unlock = 0;
+static int shared = 0; +static int shared = 0;
+static int waitonly = 0; +static int waitonly = 0;
+static int try_lock = 0;
+static int fd; +static int fd;
+static char *file; +static char *file;
+ +
...@@ -65,6 +66,7 @@ ...@@ -65,6 +66,7 @@
+ " -s Use shared locking\n" + " -s Use shared locking\n"
+ " -u Unlock\n" + " -u Unlock\n"
+ " -w Wait for the lock to become free, don't acquire lock\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); + "\n", name);
+ exit(1); + exit(1);
+} +}
...@@ -95,6 +97,7 @@ ...@@ -95,6 +97,7 @@
+static int do_lock(void) +static int do_lock(void)
+{ +{
+ int pid; + int pid;
+ int flags;
+ char pidstr[8]; + char pidstr[8];
+ +
+ if ((fd = open(file, O_RDWR | O_CREAT | O_EXCL, 0700)) < 0) { + if ((fd = open(file, O_RDWR | O_CREAT | O_EXCL, 0700)) < 0) {
...@@ -104,7 +107,10 @@ ...@@ -104,7 +107,10 @@
+ } + }
+ } + }
+ +
+ 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); + fprintf(stderr, "Can't lock %s\n", file);
+ return 1; + return 1;
+ } + }
...@@ -156,6 +162,9 @@ ...@@ -156,6 +162,9 @@
+ case 'u': + case 'u':
+ unlock = 1; + unlock = 1;
+ break; + break;
+ case 'n':
+ try_lock = 1;
+ break;
+ } + }
+ } + }
+ c--; + c--;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment