系统相关
首页 > 系统相关> > CodeGo.net>如何锁定/解锁跨进程的文件?

CodeGo.net>如何锁定/解锁跨进程的文件?

作者:互联网

使用在Linux上的mono上运行的C#,请注意以下代码在Windows上可以很好地运行,可以跨进程锁定文件,但在Linux上不能通过mono(ubuntu 14.04)

new FileStream("myfile.lock",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);

来自互联网的研究,我应该可以用advisory lock做到

FileStream.Lock

但是,它不起作用.在ubuntu 14.04上使用两个进程进行了测试,它们两个都可以执行“ FileStream.Lock(0,int.MaxValue)”.我希望以后的版本会因source code而失败.

有人知道有什么解决办法吗?

解决方法:

从单邮件列表“ http://mono.1490590.n4.nabble.com/File-Locking-td4663839.html”获得帮助

以下是“爱德华·内德·哈维(单声道)”的答案

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.

标签:locking,mono,linux,c
来源: https://codeday.me/bug/20191119/2032935.html