Question

I try to write to file while it is opened as file mapped from another process and it fails.

Please look at fragments of code:

access = GENERIC_READ | GENERIC_WRITE;
share = FILE_SHARE_READ | FILE_SHARE_WRITE;
disposition = OPEN_EXISTING;

HANDLE fileHandle = CreateFileA(fileName.c_str(), access, share, 0, disposition, 0);

//...

unsigned long valProtect = 0;

//...

valProtect = PAGE_READWRITE;

//...

const HANDLE mappingHandle = CreateFileMapping(fileHandle, 0, valProtect, 0, 0, 0);


//...

this->m_access = FILE_MAP_ALL_ACCESS;

//...

this->m_startAddress = (uint8_t*)MapViewOfFile(mappingHandle, this->m_access, 0, 0, 0);

//...

CloseHandle(fileHandle);

At this time file is closed (it's handle) but mapped to address space. I open this file in notepad++, modify it and try to save, but I see message:

"Please check if this file is opened in another program."

So I cannot rewrite it from another process, seems like it's permissions for writing is locked.

If I unmapped file like:

UnmapViewOfFile(this->m_startAddress);

Then I cannot rewrite file again.

What I did wrong?

Was it helpful?

Solution

Notepad++ is likely trying to obtain exclusive access to the file when writing to it, which will fail while the mapping (or anything else using the file) is still open. Many apps obtain exclusive access when writing to files, to avoid other processes reading the data until it is finished being written. You are sharing your file, but Notepad++ is simply asking for too many rights. There is nothing you can do about that in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top