I have a win32 app opening a log file on a network share using CreateFile and WriteFile (non overlapped) to write records. What I am seeing when the network share is lost, WriteFile reports an error (59 or 53), but an empty record (zero bytes) of the correct size is written to the file. When the share comes back online, I can see the valid data previously written and the empty records for the time that the share was lost. At the same time as the share disconnect, GetFileSize and SetFilePointer can't see any errors, but instead report the changed files as new records get added.
How does WriteFile fail when a shared file is offline ?
Happens on server 2012 ,2019, mapped drive.
Opening of the file:
hFile=CreateFile(filename,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
if (hFile==INVALID_HANDLE_VALUE && GetLastError()==ERROR_FILE_NOT_FOUND)
hFile=CreateFile(filename,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,CREATE_NEW,0,NULL);
Writing data:
if (!WriteFile(hFile,(LPCVOID)&data,sizeof(data),&bytes,NULL) || bytes==0)
{
lasterror=GetLastError();
The file is kept open all the time.
CreateFile()introduces a TOCTOU race condition. You don't need 2 calls, just 1 call will suffice usingOPEN_ALWAYSinstead ofOPEN_EXISTING+CREATE_NEWseparately.