Article ID: 316609 - View products that this article applies to.
This article was previously published under Q316609
When you open a file with the FILE_SHARE_READ flag and the FILE_SHARE_WRITE flag, the CreateFile function may fail and return the following error message:
ERROR_SHARING_VIOLATION (error code 32)
When you open a file by using the CreateFile function or any function that uses CreateFile internally, you may experience an unexpected failure because of a sharing violation. Even if the file is only for a specific application, there are potentially other processes that may try to access the file at the same time. There are common system components and also other third-party applications that cause this problem. There are common system components and also third-party applications (such as virus-scanning software) that cause this problem.
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:
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:
This method for gracefully handling the sharing violation error gives an application that has the file open time to complete. Each time that you receive a sharing violation error, you must permit the application to sleep for a while, and then try again. If a virus scanner or a system service has the file open, the virus scanner or the system service may finish after one or two retries. Make sure that you limit your retries to avoid an infinite loop. If another application currently has the file open (and may keep the file open for a long time), inform the user by breaking out of the loop, and then gracefully exit.
Article ID: 316609 - Last Review: November 21, 2006 - Revision: 1.2
Contact us for more help
Connect with Answer Desk for expert help.