DCSIMG
The Case of the Unexplained Sharing Violation - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

The Case of the Unexplained Sharing Violation

(pardon to Mark Russinovich for the title “The case of…”).

This seemingly innocent code caused a sharing violation error (32) after a few iterations:

   for(int i = 0; i < 10000; i++) {

      sprintf_s(text, "Text from process %d\r\n", GetCurrentProcessId());

 

      HANDLE hFile = CreateFile(_T("c:\\temp\\test.txt"), GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);

      if(hFile == INVALID_HANDLE_VALUE) {

         DWORD err = ::GetLastError();

         printf("Error opening file %d (%d)\n", err, i);

         break;

      }

 

      SetFilePointer(hFile, GetFileSize(hFile, NULL), NULL, FILE_BEGIN);

      DWORD bytes;

      WriteFile(hFile, text, strlen(text), &bytes, NULL);

      CloseHandle(hFile);

   }

It’s a simple loop, that opens a file, sets its file pointer to the end of the file, adds a string and closes the file. After a few iterations the CreateFile call fails with GetLastError returning 32 (sharing violation). This happens on some machines but not all. Sharing violation? Who else is opening my private file? It seems that no one.

If I open Process Explorer, press Ctrl+F and type test.txt to look for any process holding a handle to that file, I get nothing. Obviously, it’s closed already – too fast to catch manually.

The solution is to use Process Monitor, another great one from SysInternals. After setting a path filter for test.txt, this is what we find when the application is executed:

 

image

SyncDemo is my executable. The culprits are clearly shown: ekrn.exe (NOD32 antivirus) and SearchProtocolHost.exe.

The solution for this code is pretty simple: as these processes open the file for reading, I just need to change the sharing settings in CreateFile:

HANDLE hFile = CreateFile(_T("c:\\temp\\test.txt"), GENERIC_WRITE,

   FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);

Thanks goes to Alon Fliess and Dima for ideas and brainstorming.

Comments List

No Comments

Leave a Comment

(required) 
(
required
)
 
(optional)
(required) 

Enter the numbers above: