August 10th, 2016

How to create a file mapping that allows others to open the file in exclusive mode?

A customer had a tool that opens files like DLLs and TLBs in order to extract information from them.

We currently use Create­File, Create­File­Mapping, and Map­View­Of­File to access the file. The problem is that the Create­File­Mapping prevents the file from being renamed or deleted, even if the Create­File opened the file with a sharing mode that permits those operations. It is our understanding that this is expected behavior.

Since DLLs and TLBs under active development are frequently deleted or overwritten, our use of Create­File­Mapping interferes with developer workflow because the user’s build will fail with a sharing violation. We were wondering if there is an alternative to Create­File­Mapping that would allow the file to be renamed, deleted, or written to. We know that we could slurp the entire file into memory and operate on the in-memory copy, but we were hoping for something less drastic.

Yes, there is something less drastic. In fact, this is the type of scenarios for which opportunistic locks were created: You want to access a file, but you don’t want your access to interfere with anybody else who wants to access the file after you get access.

For a code sample, I defer to my earlier discussion of opportunistic locks.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.