views:

50

answers:

2

I want to be able to lock a file in Win32 so that it can only be used by my current process. The most obvious way to accomplish that seemed to be via CreateFile:

HANDLE file = ::CreateFile("c:\\foo.txt", 
                           GENERIC_READ | GENERIC_WRITE,
                           0,
                           NULL,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL);

However once that call has succeeded, the file is also apparently locked by my own process, ie. I get a "sharing violation" once the MFC framework stuff tries to open it.

Is there a convenient way to prevent access to the file by other processes but still allow it by mine? I'd rather not have to replace all the loading/saving framework code... Am I doing something wrong in the parameters I'm passing in to CreateFile?

+1  A: 

I'm not aware of any simple way to do this. As far as more complex methods go, you could:

  1. set up a special user name for accessing the file.
  2. Open the file non-shared.
  3. Edit the ACL to allow use only from the special user name
  4. Close the file.
  5. Impersonate that user
  6. Open the file, allowing sharing
  7. Close the file
  8. Set the ACL back to allow other users access

Note that I'm not saying I'd recommend that at all -- it's ugly and more or less an abuse of the system -- but if you're sure you need to do this, it's one way that probably would work.

Jerry Coffin
+2  A: 

From Creating and Opening Files:

An application also uses CreateFile to specify whether it wants to share the file for reading, writing, both, or neither. This is known as the sharing mode. An open file that is not shared (dwShareMode set to zero) cannot be opened again, either by the application that opened it or by another application, until its handle has been closed. This is also referred to as exclusive access.

See also How do the FILE_SHARE_* bits interact with the desired access bits?

Remus Rusanu