Should I name my file mapping after the file it was created from?
Many times a customer creates a file mapping object and assigns it a name that matches the name of the file it was created from. Mind you, there needs to be some fiddling with the name because backslashes are not allowed in object names (aside from the
Global\ prefix), so typically people change backslashes to forward slashes, resulting in file mappings named, for example
Is this a problem?
First, let’s put on our kernel-colored glasses.
From the kernel’s standpoint, there’s nothing wrong with this. You can name your file mappings anything you want. You can name them after the file they were created from. You can name them after your cat. You can give them a misleading name. The kernel doesn’t care, as long as you give a legal name. So sure, go ahead and name your file mapping after the file it was created from.
Okay, let’s take off our kernel-colored glasses and look at the bigger picture.
Suppose you name your file mapping after the file it was created from. And suppose somebody else does the same thing. Now you have a name collision. Your attempt to create a file mapping will succeed but also report
EXISTS, to indicate that instead of creating a new file mapping, the system gave you an existing one with that name.
The catch is that the file mapping the system gave you may not be the one you want. It may have been created with the wrong security attributes, or created with the wrong page protection, or created with the wrong size. (And by “wrong” I mean “with values that are different from what you expected.”)
That’s the thing about sharing a namespace with others: If you give your objects too obvious a name, somebody else may choose the same obvious name. We’ve seen this before in another context.
But let’s step back again: Why are you giving your file mappings names? Do you really intent to share them? Or are you just giving them names because it’s nice to give names to things? You can name your car, and you can name your kernel objects, but there is a qualitative difference between the two.
If you don’t intend the file mapping to be shared, then don’t give it a name. Giving it a name means that you intend to share it, and the name is how people can access the shared handle.
If you really do intend the file mapping to be shared, say, with other instances of the same program, then you should use a name that only your program uses. For example, you could prefix a fixed GUID to the name, so that all file mapping names used by your program have the form
file.txt. Since only your program uses that GUID, it won’t conflict with names used by other programs.
(You can think of prefixing the GUID to the mapping name as a poor man’s way of creating a namespace.)