I'm trying to prevent a third-party DLL in my process from reading a file I've opened, and I've found it to be... well, impossible.
No matter what I do, no matter what share flags I specify, their call always seems to succeed!
Here is the screenshot from Process Monitor -- the first CreateFile
call is mine, and the rest are theirs:
How is this even possible? Why is the "Share Mode: None" lying to me, and how can I prevent this?
This code below is an example that reproduces the problem:
#include <stdio.h>
#include <Windows.h>
int main()
{
LPCTSTR file = TEXT("C:\\Test1234.xml");
HANDLE hFile1 =
CreateFile(file, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_ALWAYS, 0, NULL);
HANDLE hFile2 =
CreateFile(file, FILE_READ_DATA, 0, NULL, OPEN_ALWAYS, 0, NULL);
DWORD n;
BYTE buf[1];
printf("%d\n", ReadFile(hFile2, buf, sizeof(buf), &n, NULL));
CloseHandle(hFile1);
CloseHandle(hFile2);
DeleteFile(file);
}
printf
is for. And I'm seeing1
(aka TRUE). Process Monitor confirms that all the creation requests (and the read request) go through with no errors, aside from the "End Of File" message onReadFile
. Did you try and run it yourself? – TaeguFILE_READ_DATA
rather thanGENERIC_READ
? Perhaps that's the problem. – CockchaferGENERIC_READ
doesn't make any difference --ReadFile
succeeds either way. Did you try reproducing the problem? The code is rather easy to run... – TaegudwDesiredAccess
parameter of bothCreateFile()
calls toGENERIC_READ
then the second call toCreateFile()
does fail as expected (I tested it). If the first call is then changed back toFILE_READ_ATTRIBUTES
then the second call succeeds. So it seems thatFILE_READ_ATTRIBUTES
andFILE_READ_DATA
are not restricted by sharing rights. – HighflownFILE_READ_ATTRIBUTES
is really special then. (And another funny thing I noticed is, apparently none of these tricks work on directory handles, only file handles -- you can't deny others access to a directory.) Would you mind posting your finding as an answer? Thanks! – Taegu