summaryrefslogtreecommitdiff
path: root/src/libstddjb/fd_lock.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/libstddjb/fd_lock.c')
-rw-r--r--src/libstddjb/fd_lock.c25
1 files changed, 25 insertions, 0 deletions
diff --git a/src/libstddjb/fd_lock.c b/src/libstddjb/fd_lock.c
new file mode 100644
index 0000000..422e667
--- /dev/null
+++ b/src/libstddjb/fd_lock.c
@@ -0,0 +1,25 @@
+/* ISC license. */
+
+#include <fcntl.h>
+#include <errno.h>
+
+#include <skalibs/error.h>
+#include <skalibs/djbunix.h>
+
+int fd_lock (int fd, int w, int nb)
+{
+ struct flock fl =
+ {
+ .l_type = w ? F_WRLCK : F_RDLCK,
+ .l_whence = SEEK_SET,
+ .l_start = 0,
+ .l_len = 0
+ } ;
+ int e = errno ;
+ int r ;
+ do r = fcntl(fd, nb ? F_SETLK : F_SETLKW, &fl) ;
+ while (r < 0 && errno == EINTR) ;
+ return r >= 0 ? 1 :
+ errno == EACCES || error_isagain(errno) ? (errno = e, 0) :
+ -1 ;
+}