Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateFile FILE_FLAG_DELETE_ON_CLOSE fails after any handle has been closed

We create a file for use as memorymappedfile.

we open with GENERIC_READ | GENERIC_WRITE
we use share with FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
we use file attributes 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 more handles, it returns with ERROR_ACCESS_DENIED. We can cause this by closing any of the handles, either the first from CreateFile(ALWAYS_CREATE), or the others from CreateFile(OPEN_EXISTING).

Is there any way to avoid this ? We use the memoryMappedFile as communication between the different processes that must share resources. these processes sometimes start and stop. Right now as soon as we close one handle, we are stuck unable to open the memorymappedfile.

I have tried changing the open calls to use FILE_ATTRIBUTE_NORMAL, so only the create call uses CLOSE_ON_DELETE but that has no effect on this situation.

like image 443
cdturner Avatar asked Apr 13 '15 21:04

cdturner


1 Answers

The problem you're running into is that once a file handle opened with FILE_FLAG_DELETE_ON_CLOSE is closed, the operating system will no longer allow new handles to be created.

The gory details: When processing an IRP_MJ_CLEANUP (which is what happens win a handle is closed) for a file opened for delete-on-close, Windows file systems will set an internal flag on the file object indicating that it's on it's way out. Subsequent open attempts on the file will be failed with STATUS_DELETE_PENDING, which the Win32 subsystem will map to the Win32 ERROR_ACCESS_DENIED code you're seeing.

For your use case, you might want to consider using the Named Shared Memory (MSDN) pattern. 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.

like image 183
Bukes Avatar answered Sep 17 '22 22:09

Bukes