0

In my application I open a handle to shared memory that I read/write to/from. I open the handle like so:

//Map the shared memory
     d_to_mbx_mem_arr[idx] = reinterpret_cast<Byte*>(MapViewOfFile(to_mem_h,    // handle to map object
                                                       FILE_MAP_ALL_ACCESS, // read/write permission
                                                       0,
                                                       0,
                                                       MAILBOX_SIZE_e));

The variable getting set here is an array of Byte* (Byte is an alias for unsigned char), so I do a reinterpret cast so I can just use the handle like a standard Byte pointer.

Later I try to release the handle in the following way:

CloseHandle(d_to_mbx_mem_arr[p_tool_id]);
d_to_mbx_mem_arr[p_tool_id] = NULL;

Since the value is getting set to NULL after CloseHandle and the code calling this method is only single-threaded I know I'm only calling this once. However when I do call it I get the following warning:

"First-chance exception at 0x7c90e4ff (ntdll.dll) in FMLib_Comm_Layer.exe: 0xC0000008: An invalid handle was specified."

When I break for the warning I see that the handle it is trying to close has a value of "0x01c90000", which seems reasonable to me for a shared mem pointer. Does anyone see a problem with this implementation, or should I assume I've screwed something else up somewhere else?

Ian
  • 4,169
  • 3
  • 37
  • 62
  • 1
    Two questions: (1) Is that handle value the same value that you get when you first obtain the handle? (2) Do you call `UnmapViewOfFile` and does that call succeed? [The order in which you call `UnmapViewOfFile` and `CloseHandle` does not matter, but you must call both of them to release the file. Both should succeed, though.] – James McNellis Jun 05 '12 at 18:26

1 Answers1

4

You need to call CloseHandle() on to_mem_h, not on the return value of MapViewOfFile() (See an example of using MapViewOfFile() here -- that example is calling UnmapViewOfFile() on the return value of MapViewOfFile() and is calling CloseHandle() on the first parameter to MapViewOfFile())

Attila
  • 28,265
  • 3
  • 46
  • 55
  • Okay, 1 question. I actually call CloseHandle on to_mem_h right after I've mapped a view of the file even though I continue to use the share file that I've mapped, is this okay? – Ian Jun 05 '12 at 20:09
  • 1
    Actually, that is in fact okay. From the `UnmapViewOfFile` documentation: "Although an application may close the file handle used to create a file mapping object, the system holds the corresponding file open until the last view of the file is unmapped." – James McNellis Jun 05 '12 at 20:30
  • Adding UnmapViewOfFile instead of CloseHandle seemed to fix it. I would be surprised if it were not okay to close the file handle while still using the file mapping object, because I've been doing it for a while now without observable issues. – Ian Jun 05 '12 at 20:48