My understanding of hard drives/filesystems is that because hard drives
are
so slow, that when you write to the harddrive, that information is put
into a buffer, control is returned to the program, and then the
information is saved to permanent storage in the near future.
Is there any way to guarantee that before my function returns, anything
written to the hard drive is Actually on the hard drive?
The data I'm getting seems to support my concern, as according to the
logs, the crash is occuring at different places each time, and
sometimes, the log file doesn't even get anything written into it
before a crash.
ben
void BKprintLog(char * line) {
FILE * file;
const char * FILENAME = "C:\\log_file.txt";
SYSTEMTIME systime;
GetSystemTime(&systime);
file = fopen(FILENAME,"a+");
fprintf(file, "%2d:%02d:%06.3lf ::
%s\n",systime.wHour,systime.wMinute,systime.wSecond+systime.wMilliseconds/1000.0,line);
fclose(file);
}
> My understanding of hard drives/filesystems is that because hard drives
> are
> so slow, that when you write to the harddrive, that information is put
> into a buffer, control is returned to the program, and then the
> information is saved to permanent storage in the near future.
If this is the system crash your data may not been written due to buffering. You can increase probability of that by adding Sleep() function after fclose if the calls to your log are not often.
Alternatively you can try to write your log to the drive which is not cached. So you may want do disable caching of your drive prior to debugging.
--
Grzegorz Wróbel
http://www.4neurons.com/
677265676F727940346E6575726F6E732E636F6D
http://www.sysinternals.com/Utilities/Sync.html
I'm not entirely sure how he did it, but a quick check with
Dependency Viewer suggests looking at FlushFileBuffers. From
what MSDN says, if you use CreateFile to get a handle to the
volume, you can flush the buffers for the whole disk.
If you change your logging function to use CreateFile/WriteFile
with FILE_FLAG_NO_BUFFERING instead of the C library functions,
that would probably work as well, but it caries additional
restrictions.
To get it to work with this API without turning off buffering,
you may be able to change your function to do the following:
DWORD dwWritten = 0;
char szBuf[some_buffer_size];
HANDLE hFile = CreateFile("C:\\log_file.txt",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
SetFilePointer(hFile, 0, NULL, FILE_END);
sprintf(...);
WriteFile(hFile, szBuf, strlen(szBuf), &dwWritten, NULL);
FlushFileBuffers(hFile);
CloseHandle(hFile);
If that doesn't work, you can always try flushing the volume, or
turning off buffering altogether.
HTH,
David