How to lock/unlock a file across process?

烈酒焚心 提交于 2021-02-08 14:22:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35444470/how-to-lock-unlock-a-file-across-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!