3
votes

I have 2 questions concerns about using shared memory. I'm using CreateFileMapping to create a shared memory area between two processes.

1) I understand that I need to call CloseHandle on every handle returned from a CreateFileMapping or OpenFileMapping call in order to release the memory. My question is, do all handles get closed appropriately and mem deallocated by Windows XP/7 if the programs using the shared memory exit without calling CloseHandle? IE - is there a possibility of a mem leak after all processes using the mem have been closed?

2) I use MapViewofFile to get a pointer to the mem. In 1 instance I've assumed that the shared memory will always exist in the context of a method. So I've saved the return value of MapViewOfFile as a pointer and closed the handle to the mem and am just using the pointer to the shared mem (but still locking access to it). Is this safe, or should I call MapViewOfFile every time I access the shared mem?

Thanks,

Ian

1

1 Answers

7
votes

1) Yes, all handles are closed when a process terminates, no matter if it dies or finishes nicely. No leaks here.

2) As long as you don't call UnmapViewOfFile, the memory will still be accesible to the process, even if the handle has been closed:

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