Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

high level file locking file interface #512

Open
wants to merge 1 commit into from

2 participants

@c-cube
Owner

Not sure if useful enough for batteries, but I found this code nice for coarse-grained concurrent updates on files.

@thelema
Owner

I like the idea behind the code, although it needs a self-test before we can accept it.

Owner

I agree, but I'm not sure of how to test this. It requires some form of threading/forking to be able to concurrently access a file, yet check that race conditions do not occur. This might raise more questions about how to test the threaded part of batteries...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 3, 2014
  1. @c-cube
This page is out of date. Refresh to see the latest.
Showing with 26 additions and 0 deletions.
  1. +19 −0 src/batUnix.ml
  2. +7 −0 src/batUnix.mliv
View
19 src/batUnix.ml
@@ -175,3 +175,22 @@ let is_directory fn = (lstat fn).st_kind = S_DIR
let rec restart_on_EINTR f x =
try f x
with Unix_error(EINTR, _, _) -> restart_on_EINTR f x
+
+(** {6 Locking} *)
+
+let with_file_lock ~kind filename f =
+ let lock_file = openfile filename [O_CREAT; O_WRONLY] 0o644 in
+ let lock_action = match kind with
+ | `Read -> Unix.F_RLOCK
+ | `Write -> Unix.F_LOCK
+ in
+ lockf lock_file lock_action 0;
+ try
+ let x = f () in
+ lockf lock_file F_ULOCK 0;
+ close lock_file;
+ x
+ with e ->
+ lockf lock_file F_ULOCK 0;
+ close lock_file;
+ raise e
View
7 src/batUnix.mliv
@@ -808,6 +808,13 @@ val lockf : file_descr -> lock_command -> int -> unit
acquired on the specified region, without actually putting a lock.
It returns immediately if successful, or fails otherwise. *)
+val with_file_lock : kind:[`Read|`Write] -> string -> (unit -> 'a) -> 'a
+(** [with_file_lock ~kind filename f] puts a lock on the offset 0
+ of the file named [filename], calls [f] and returns its result after
+ the file is unlocked. If [f ()] raises an exception the exception is
+ re-raised after the file is unlocked.
+
+ @param kind specifies whether the lock is read-only or read-write. *)
(** {6 Signals}
Note: installation of signal handlers is performed via
Something went wrong with that request. Please try again.