There is a process that is writing to a file running on my local Linux machine. It has a 'Write' lock. I can verify this using sudo lslocks | grep myFile.txt
myApplication 2810 FLOCK 4.5M WRITE 0 0 0 /var/opt/myApplication/logs/myFile.txt
Note that this is not a mandatory lock, it's advisory. Also note, I'm able to read this file using vi or cat. I can even open it using a few lines of Python:
f = open("/var/opt/myApplication/logs/myFile.txt", "r")
print(f.readline())
But I haven't been able to open it using C#. I've tried several different ways but they all fail. The same code, when run on Windows using the Windows version of the same external process that is writing to the file, appears to work just fine.
Here is the C# code that I believed would have worked.
var fileInfo = new FileInfo("/var/opt/myApplication/logs/myFile.txt");
var file = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
This code fails and an IO Exception is thrown saying:
The process cannot access the file '/var/opt/myApplication/logs/myFile.txt' because it is being used by another process.
The exception seems to come from inside FileStream.Unix.cs as a result of the call to Interop.Sys.FLock returning an error:
Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH;
if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0)
I don't have the ability to change the process that is writing to this file, though, the output of lslocks seems reasonable enough to me...but I really need a way read the contents of the file. Is there an alternative way to do this with dotnet, especially given it seems so trivial in other languages?
Update: No idea if this matters or not (I assume not), but this is all on a CentOs 7 installation