Reputation: 2200
I'm opening files using the _findfirst
function in windows, but I will only want to open files which are not opened by other process. The situation is that I will scan a directory read the files and delete them while other process create new files in it.
To avoid race conditions I found this question which mentions the possibility to open a file with a no sharing
option. But how is that done?
Update: I have no control about the writing process, so don't know which flags, if nay, are used when creating a file. Moreover the writing process may change (third party software).
Upvotes: 2
Views: 1988
Reputation: 331
Assuming that your 2 processes are the only ones that will open the files then, from MSDN open sample:
hFile = CreateFile(argv[1], // name of the write
GENERIC_WRITE, // open for writing
0, // *** do not share ***
NULL, // default security
CREATE_NEW, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
By using this in your writing process you can then check for INVALID_HANDLE_VALUE in the reading process and in this case if GetLastError() returns ERROR_SHARING_VIOLATION then you know that your file is opened by another process with no sharing.
More details can be found in the CreateFile documentation
Upvotes: 3
Reputation: 381
to open a file with no sharing option, you can use
HANDLE hFile = CreateFile("somFileName",
GENERIC_WRITE,
0, /*no sharing; other options are FILE_SHARE_READ, FILE_SHARE_WRITE etc*/
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
Upvotes: 1
Reputation: 36483
Call OpenFile and as uStyle
(third param) add at least OF_SHARE_EXCLUSIVE
.
Upvotes: 1