Skip to content

Instantly share code, notes, and snippets.

@allanjude
Created December 4, 2020 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allanjude/4d39962873e746ce7abbe21a10271ed4 to your computer and use it in GitHub Desktop.
Save allanjude/4d39962873e746ce7abbe21a10271ed4 to your computer and use it in GitHub Desktop.
FreeBSD lockf made to work on Linux
--- /usr/src/usr.bin/lockf/lockf.c 2019-05-04 13:19:22.297590000 -0400
+++ lockf_linux.c 2020-12-04 14:49:25.770507000 -0500
@@ -25,9 +25,6 @@
* SUCH DAMAGE.
*/
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD: releng/12.0/usr.bin/lockf/lockf.c 326276 2017-11-27 15:37:16Z pfg $");
-
#include <sys/types.h>
#include <sys/wait.h>
@@ -171,11 +168,16 @@
{
int fd;
- if ((fd = open(name, O_RDONLY|O_EXLOCK|flags, 0666)) == -1) {
+ if ((fd = open(name, O_RDONLY|flags, 0666)) == -1) {
if (errno == EAGAIN || errno == EINTR)
return (-1);
err(EX_CANTCREAT, "cannot open %s", name);
}
+ if ((flock(fd, LOCK_EX | (flags & O_NONBLOCK ? LOCK_NB : 0))) == -1) {
+ if (errno == EAGAIN || errno == EINTR)
+ return (-1);
+ err(EX_CANTCREAT, "failed to acquire lock %s", name);
+ }
return (fd);
}
@@ -210,7 +212,7 @@
* Signal handler for SIGALRM.
*/
static void
-timeout(int sig __unused)
+timeout(int sig)
{
timed_out = 1;
@@ -234,10 +236,15 @@
{
int fd;
- if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) {
+ if ((fd = open(name, O_RDONLY, 0666)) == -1) {
if (errno == ENOENT || errno == EINTR)
return;
err(EX_CANTCREAT, "cannot open %s", name);
+ }
+ if ((flock(fd, LOCK_EX)) == -1) {
+ if (errno == ENOENT || errno == EINTR)
+ return;
+ err(EX_CANTCREAT, "cannot lock %s", name);
}
close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment