Why does CreateFileMapping return "file already exists"?

I have an application that has a shared memory zone defined using CreateFileMapping , and I'm trying to read this memory from another application.

I tried this:

 handle := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0,$3200, pchar('FileMappingZone')); 

But I get:

Unable to create file if this file already exists

What could be the problem?

+7
source share
1 answer

Not everything that sets GetLastError() to failure is an error. It is important to first recognize the errors using the return value of the function and examine GetLastError() to get more information about the error that occurred.

For existing mappings, CreateFileMapping documented to return a valid handle and set the value of GetLastError() to ERROR_ALREADY_EXISTS . In this case, the meaning of the error is informative: it is valid for checking it, if you are interested in whether there is a comparison before opening it, but this is not an error. You encounter an error by checking the return value for NULL. Otherwise, you just continue to use the pen.

PS If you want to make sure that the section exists before opening, you can use OpenFileMapping , which will fail for non-existent sections instead of creating a new one.

+15
source

All Articles