Skip to content

Instantly share code, notes, and snippets.

@mrvaldes
Last active February 16, 2016 22:29
Show Gist options
  • Save mrvaldes/6196035 to your computer and use it in GitHub Desktop.
Save mrvaldes/6196035 to your computer and use it in GitHub Desktop.
advisory locking example in Mono C#
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;
}
@cmcqueen
Copy link

Note that this implements fcntl() locking, which is different from flock() locking in Linux (despite the name of the structure Flock).

I'm interested to do flock() style locking in Linux, but I don't think Mono provides a way to do it.

@shrimpywu
Copy link

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