Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!