CreateFile FILE_FLAG_DELETE_ON_CLOSE crash after closing any handle

We create a file for use as a memory file.

open with GENERIC_READ | GENERIC_WRITE GENERIC_READ | GENERIC_WRITE
we use share with FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
we use file attributes FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE

We create the file successfully. We can reopen it as many times with the same flags as we want.

Once one handle has been closed, we can no longer open any handles, it returns with ERROR_ACCESS_DENIED. We can call this by closing any of the handles, either from CreateFile (ALWAYS_CREATE) or from CreateFile (OPEN_EXISTING).

Is there any way to avoid this? We use memoryMappedFile as a connection between different processes that need to share resources. these processes sometimes begin and stop. Right now, when we close one descriptor, we cannot open the file with memory.

I tried changing the open calls to use FILE_ATTRIBUTE_NORMAL, so only the create call uses CLOSE_ON_DELETE, but this does not affect this situation.

+6
source share
2 answers

The problem you are having is that after the file descriptor opened with FILE_FLAG_DELETE_ON_CLOSE is closed, the operating system will no longer be able to create new descriptors.

Information about gory: when processing IRP_MJ_CLEANUP (what happens when the handle is closed) for a file opened for delete-on-close, Windows file systems set an internal flag in the file object, indicating that it exits. Subsequent attempts to open the file will fail with STATUS_DELETE_PENDING , which the Win32 subsystem will display in the Win32 code ERROR_ACCESS_DENIED that you see.

In your use case, you may need to use the Named Shared Memory (MSDN) template. Basically, let the operating system manage the space for your shared memory. Just make sure you apply the appropriate security attributes, and you're good to go.

+10
source

It turns out that the venerable Raymond Chen answered this on his Microsoft developers blog, The Old New Thing. Bukes is right, but as an alternative, as Raymond says in his article:

It seems like they really want the file to remain valid (including allowing further calls to CreateFile to succeed) as long as any open descriptor continues to reference the file. Fortunately, the client only needed a handle to create a mapping with a mapping in memory. The file pointer was not important. Therefore, the client can use DuplicateHandle instead of CreateFile to get additional file descriptors. Since all descriptors refer to the same file object, the file object will not delete the file until all descriptors are closed.

0
source

Source: https://habr.com/ru/post/985090/


All Articles