Using C# running on mono on Linux, notice that below code works well on windows can lock a file across process but not on linux via mono (ubuntu 14.04)
new FileStream("myfile.lock",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);
research from internet, i should be able to do it with advisory lock
FileStream.Lock
however, it doesn`t work. tested with two processes on ubuntu 14.04, both of them can execute "FileStream.Lock(0, int.MaxValue)". i would expect the later one will fail with exception per source code.
anyone know is there any solution?
The easiest way to unlock the file is to end the process that has locked it. But it is not always possible, especially on the servers. To find a process that has locked a file, it is often recommended to use the Unlocker tool.
It allows you to find a process having locked your file and release the lock by freeing the handle. Open the command prompt as an administrator and run the following command: handle64.exe > listproc.txt This command will save the list of open handles to a txt file.
We can also see detailed information of each lock, such as the lock type, and which process holds the lock. /proc/locks is not a command. Instead, it is a file in the procfs virtual file system. The file holds all current file locks. The lslocks command relies on this file to generate the list, too.
There is no need to install ProcessExplorer: we can simply download, extract and run procexp.exe as administrator 2. First, we select Find >> Find Handle or DLL (or press Ctrl-F) 3. Then we need to specify the file name that we want to unlock and then we click Search 4. Here, we select the file we want.
Get help from mono mail list "http://mono.1490590.n4.nabble.com/File-Locking-td4663839.html"
below is the answer quote from "Edward Ned Harvey (mono)"
Kinda sorta. The underlying issue is that OSX, Linux, and Windows all have different underlying file locking constructs, and then of course, there's some variability about even which filesystem is being used. I didn't thoroughly figure out all the answers for every OS or filesystem, and I don't know under which situations this will be good enough, but this is what I ended up using, works under the conditions we needed it to work:
using (var foo = new FileStream(filePath, FileMode.Open,FileAccess.ReadWrite, FileShare.None)) { // must include Write access in order to lock file
foo.Lock(0, 0); // 0,0 has special meaning to lock entire file regardless of length
}
For windows, simply specifying the FileAccess and FileShare is good enough. For linux, at least ext4, files are concurrently readable regardless of what you specify for FileAccess and FileShare. The Lock() method does something of a soft-lock. It's not enforced by the OS, but at least all the situations we tried, other client apps honor the lock. Didn't look into it any deeper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With