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.
GetLastError
unconditionally after each call? It's expected forCreateFileMapping
to return a valid handle and for the followingGetLastError
to returnERROR_ALREADY_EXISTS
(which is not actually an error if it's what you expect). – Anton KovalenkoGetLastError
when the documentation says to do so. And that is whenCreateFileMapping
returnsNULL
. – David HeffernanGetLastError
is supposed to be examined in non-error cases sometimes, unlikeerrno
. But then it's important not to interpret its value as an error. – Anton Kovalenko