Last active
February 16, 2016 22:29
-
-
Save mrvaldes/6196035 to your computer and use it in GitHub Desktop.
advisory locking example in Mono C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Mono.Unix.Native; | |
using System.IO; | |
static bool TryLockProcess(string file_to_lock) | |
{ | |
int pid = Syscall.getpid(); | |
int fd = Syscall.open(file_to_lock, OpenFlags.O_CREAT | OpenFlags.O_RDWR, FilePermissions.DEFFILEMODE); | |
if (fd > 0) { | |
// a write (exclusive) lock | |
Flock wl; | |
wl.l_len = 0; | |
wl.l_pid = pid; | |
wl.l_start = 0; | |
wl.l_type = LockType.F_WRLCK; | |
wl.l_whence = SeekFlags.SEEK_SET; | |
// try to set lock | |
int res = Syscall.fcntl(fd, FcntlCommand.F_SETLK, ref wl); | |
// if can't get lock ... | |
if (res != 0 || Syscall.GetLastError() == Errno.EAGAIN) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
return false; | |
} |
doesn`t seems to work anymore (Ubuntu 14.04). is there any updated version?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this implements
fcntl()
locking, which is different fromflock()
locking in Linux (despite the name of the structureFlock
).I'm interested to do
flock()
style locking in Linux, but I don't think Mono provides a way to do it.