How can CreateFile crash with FILE_SHARE_READ and succeed with FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE?

Try it yourself:

Create a XLS file, open it in Excel.

Open sysinternals Process Monitor and see what happens when you make a copy of your XLS file in Explorer (just press ctrl-c ctrl-v).

Two calls ::CreateProcess in a line. The first call requests read permission and access is denied. The second call requests read plus write plus delete and pass.

This is normal?

+6
windows file-io process winapi
source share
2 answers

If you open a file with FILE_SHARE_READ , you say that you agree to grant access to this file, but only for reading.

If you open all the flags, you can also share for writing / deleting.

FILE_SHARE_READ more restrictive than FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE

If any other process (excel) opened this file, for example, write (and it has the exchange flags set), the only way you can access it is to accept its sharing for writing.

+11
source share

You must use compatible sharing modes. If Excel opens a file with FILE_SHARE_READ | FILE_SHARE_WRITE, subsequent attempts to open the file must use at least the same flags. In particular, from the MSDN documentation for CreateFile :

You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request with an open descriptor. CreateFile will fail and GetLastError will return ERROR_SHARING_VIOLATION.

+3
source share

All Articles