windowsunixfile-locking

How do I make Windows file-locking more like UNIX file-locking?


UNIX file-locking is dead-easy: The operating system assumes that you know what you are doing and lets you do what you want:

For example, if you try to delete a file which another process has opened the operating system will usually let you do it. The original process still keeps it's file-handles until it terminates - at which point the the file-system will quietly re-cycle the disk-resources. No fuss, that's the way I like it.

How different things are on Windows: If I try to delete a file which another process is using I get an Operating-System error. The file is untouchable until the original process releases it's lock on the file. That was great back in the single-user days of MS-DOS when any locking process was likely to be on the same computer that contained the files, however on a network it's a nightmare:

Consider what happens when a process hangs while writing to a shared file on a Windows file-server. Before the file can be deleted we have to locate the computer and ID the process on that computer which originally opened the file. Only then can we kill the process and delete our unwanted file.

What a nuisance!

Is there a way to make this better? What I want is for file-locking on Windows to behave a like file-locking in UNIX. I want the operating system to just let me do what I want because I'm in charge and I know what I'm doing...

...so can it be done?


Solution

  • According to MSDN you can specify to CreateFile() 3rd parameter (dwSharedMode) shared mode flag FILE_SHARE_DELETE which:

    Enables subsequent open operations on a file or device to request delete access.

    Otherwise, other processes cannot open the file or device if they request delete access.

    If this flag is not specified, but the file or device has been opened for delete access, the function fails.

    Note Delete access allows both delete and rename operations.

    http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx

    So if you're can control your applications you can use this flag.