0
votes

My application works on a highly sensitive file. Normally - this file is NOT shared among others and is accessed exclusively by my APP. Therefore it is opened as follows:

DWORD   dwShareMode = 0; // Exclusive no share
hFile = CreateFile(
    pszSrc,             // file to open
    GENERIC_READ | GENERIC_WRITE,   // open for reading
    dwShareMode,            // No share!!
    NULL,               // default security
    OPEN_EXISTING,          // existing file only
    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
    NULL);                 // no attr. template

However - there are certain circumstances under which my APP should allow others to read certain portions of this file. This should be carried out without any other sharing mechanism: No locks,no mutexs no nothing of that kind. In addition to that - my APP MUST keep this file open at all times. No close/re-open is applicable under the critical mission terms of this APP.

My question is: Is there a way to dynamically change the SHARE-MODE of the file associated with a handle while it is open? Practically speaking - can one open a file for EXCLUSIVE share and change it thereafter to - say - FILE_SHARE_READ | FILE_SHARE_WRITE - back and forth?

Thanks

E.

2
For the record, those requirements don't make sense. - Harry Johnston

2 Answers

2
votes

You are going to need to re-open the file with a new share mode, but you can do it without closing it, see ReOpenFile

HANDLE newHandle = ReOpenFile(origHandle,
                             FILE_GENERIC_READ | FILE_GENERIC_WRITE,
                             FILE_SHARE_READ, 0);
2
votes

You should simply open the file with FILE_SHARE_READ and use the Access Control List to prevent unauthorised user processes from reading the file.

To coordinate access between the processes accessing the file, you should use the LockFile/UnlockFile family of APIs.

With LockFile you can lock the file so that, even though another process can open it, with read access, they cannot read it until you unlock it with UnlockFile.

Note that you can lock regions which are outside the allocated file size. So to lock the whole file:

LockFile(hFile, 0x0, 0x0, 0xffffffff, 0xffffffff);

// To unlock it:
UnlocFile(hFile, 0x0, 0x0, 0xffffffff, 0xffffffff);

You should note that neither opening the file for exclusive access, nor locking regions of the file, are security mechanisms. In particular they do not prevent administrative users from reading the file using the backup APIs.