MonoThreaded
MonoThreaded

Reputation: 12033

Notepad beats them all?

On a Windows Server 2012 R2 system, a Kotlin program uses FileChannel.tryLock() to hold an exclusive lock on a file, like this:

val fileRw = RandomAccessFile(file, "rw")
fileRw.channel.tryLock()

With this lock in place, I cannot open the file with:

I can open it with Notepad.

How the heck is Notepad able to open a locked file that nothing else can?

Upvotes: 148

Views: 31583

Answers (1)

Iridium
Iridium

Reputation: 23721

Notepad reads files by first mapping them into memory, rather than using the "usual" file reading mechanisms presumably used by the other editors you tried. This method allows reading of files even if they have an exclusive range-based locks.

You can achieve the same in C# with something along the lines of:

using (var f = new FileStream(processIdPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var m = MemoryMappedFile.CreateFromFile(f, null, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, true))
using (var s = m.CreateViewStream(0, 0, MemoryMappedFileAccess.Read))
using (var r = new StreamReader(s))
{
    var l = r.ReadToEnd();
    Console.WriteLine(l);
}

Upvotes: 216

Related Questions