123456789101112131415161718192021222324252627typet=Unix.file_descrletcreate_internaloppath=Path.mkdir_p(Path.parent_exnpath);letfd=Unix.openfile(Path.to_stringpath)[Unix.O_CREAT;Unix.O_RDWR]0o600andpid=string_of_int(Unix.getpid())inletpid_len=String.lengthpidin(* fcntl would enable to downgrade the lock to a read lock so other process
can read the PID, but it is not bound in Unix *)matchUnix.lockffdop0;assert(Unix.single_write_substringfdpid0pid_len=pid_len)with|()->Somefd|exceptionUnix.Unix_error(EAGAIN,_,_)->Unix.closefd;None|exceptione->Unix.closefd;Exn.reraiseeletcreatepath=Option.value_exn(create_internalF_LOCKpath)lettry_create=create_internalF_TLOCKletunlockfd=Unix.closefd