Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CreateFileMapping return "file already exists"?

I have an application which has a shared memory zone defined with CreateFileMapping and I am trying to read that memory from another application.

I tried this:

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

But I get:

Cannot create a file when that file already exists

What could be the problem?

like image 676
opc0de Avatar asked Feb 07 '13 11:02

opc0de


1 Answers

Not everything which sets GetLastError() value to non-success is an error. It's important to distinguish errors by function's return value first, and examine GetLastError() to get more information on the kind of error that happened.

For mappings that already exist, CreateFileMapping is documented to return a valid handle and to set GetLastError() value to ERROR_ALREADY_EXISTS. In this case, error value is informational: it's valid to examine it if you're interested whether the mapping was existing before you opened it, but it's not an error. You detect failure by testing the return value for being NULL. Otherwise you just go ahead and use the handle.

P.S. If you want to ensure that the section exists before opening, you may use OpenFileMapping which will fail for non-existing sections instead of creating a new one.

like image 124
Anton Kovalenko Avatar answered Nov 19 '22 02:11

Anton Kovalenko