The Microsoft Windows operating system is a preemptive, multiprocessing system, which gives the appearance of many applications running simultaneously. Any particular application must be "aware" that it is not the only process running on the system and that it is vying for resources with other processes. Problems that may occur because of resource handling must be addressed. In the case of files, any running process has the right to try to use the resource. There are always system components and third party services that compete for resources simultaneously. When an application tries to access files on the system, that application competes with the other processes.
There are two common causes for an ERROR_SHARING_VIOLATION:
- There are multiple applications that use a particular file on disk (common shared data files). An application is currently accessing the file in a way that is incompatible with the way a second application tries to access the same file. For example, you may want to update the file, but another process is currently writing to the file and is only sharing the file for reading (FILE_SHARE_READ).
- The file is a data file specific to your application, and you do not expect another application to have the file open. In this scenario, other processes may lock a file for a short duration for other reasons.
Both of the causes for sharing violations described earlier must be handled similarly. When you open a file, you must always handle a sharing violation in a graceful manner so that you do not affect the user of the system or cause the system to crash. You can do this by using a simple retry mechanism. You may have to perform multiple retries before the file is unlocked.
The following code sample demonstrates this technique:
#define MAXRETRIES 5
#define RETRYDELAY 250
HANDLE hFile = INVALID_HANDLE_VALUE
DWORD dwRetries = 0;
BOOL bSuccess = FALSE;
DWORD dwErr = 0;
hFile = CreateFile( szFile,
FILE_SHARE_READ | FILE_SHARE_WRITE,
if ( INVALID_HANDLE_VALUE == hFile )
dwErr = GetLastError();
if ( ERROR_SHARING_VIOLATION == dwErr )
dwRetries += 1;
// An error occurred.
bSuccess = TRUE;
} while ( dwRetries < MAXRETRIES );
if ( bSuccess )
// You succeeded in opening the file.
// Failure occurs. Do graceful error handling.
// Here, you must notify the user of the failure.
"Tried to update data file but it was already in use",
MB_OK | MB_ICONSTOP );
// You also want to put the software back in the state it was in
// on entrance of the current function, as if the user had never
// tried to do the update.
// This may also require deallocating any resources that were
// allocated because of this operation.