简体   繁体   中英

How to lock/unlock a file across process?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM