We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now


Locking a File

Intern asked
Medium Priority
Last Modified: 2011-09-20
I have a program that will be run via RF connection.  There will be multiple handhelds running this program, which means that one computer will be running multiple instances of the program.  The problem is that I need to be able to lock a file and make the other instances wait until the file is unlocked.

I am using one file (call it GLOBAL.TXT) and this file will be read from and written too by multiple instances of 2 different programs.  Can someone start me off on how to lock the file and make the other files wait there turn?  Sometype of a empty loop that runs until the file is unlocked?

Thanks for any help.
Jordan Marshall
Watch Question

Open file in exclusive mode.


Will that make the other programs wait?  or will they fail?  

"exclusive mode" - as in  file.open("GLOBAL.TXT", "something")

or am I off?  if not can you fill me in on the "something" part

If you open a file in write mode, it will be in exclusive mode by default. Other open calls will fail. You could add a loop to the open code that will repeatedly attempt to open the file until it succeeds. It would probably be wise to wait a little bit between open attempts. Something like, in psuedo code:

{    attempt to open file
      if failed, wait a bit
} while(file open failure)

You can do this with fopen(), but I will assume you are using MFC's CFile class.  I makes me comfy to explicitly include the flags that do what I want.  It is easier to discern what is going on in the code when reading it.

MyFileMgr::Open() {

Unlock this solution and get a sample of our free trial.
(No credit card required)
You could use a Mutex to lock other programs using the same resource.

Look at this sample from MSDN (if you are using MFC you may use class CMutex instead)


HANDLE hMutex;

hMutex = CreateMutex
      NULL,                             // no security attributes
      FALSE,                            // initially not owned
      "MutexToProtectDatabase");        // name of mutex

if (hMutex == NULL)
                                        // Check for error.

When a thread of this process writes to the database, it first requests ownership of the mutex. If it gets ownership, the thread writes to the database and then releases its ownership.

The example uses the try-finally structured exception-handling syntax to ensure that the thread properly releases the mutex object. To prevent the mutex object from being abandoned inadvertently, the finally block of code is executed no matter how the try block terminates — unless the try block includes a call to the TerminateThread function.

BOOL FunctionToWriteToDatabase(HANDLE hMutex)
      DWORD dwWaitResult;

      dwWaitResult = WaitForSingleObject(
         hMutex,        // handle of mutex
         5000L);        // five-second time-out interval
      switch (dwWaitResult)
         case WAIT_OBJECT_0:
                        // Write to the database.

               if (! ReleaseMutex(hMutex))
                        // Deal with error.


                        // Cannot get mutex ownership due to time-out.
        case WAIT_TIMEOUT:
            return FALSE;

                        // Got ownership of the abandoned mutex object.
        case WAIT_ABANDONED:
            return FALSE;

      return TRUE;


The mutex is named "MutexToProtectDatabase" and you can get a handle to it by using CreateMutex(...) from threads of different processes.

Regards, Alex



In your example (which I think is what I need) I need to put a loop in place to keep trying to open the file.  What is a good command to use that will make the computer wait for a little bit before tyring again?  I have never had to do this and don't really know what to use.


That will wait 10 milliseconds.

Regards, Alex

You can use Sleep(), as mentioned above -- the argument is the number of milliseconds, but ideally, after a couple seconds or less total of Sleep()ing, you should put up a modeless dialog box with a Cancel button, in case the user gets tired of waiting.  A tight loop with a Sleep is essentially an infinite loop that you are hoping will break free because the resource has gotten freed.  Having said that, the code could be rewritten to the following (not compiled or tested):

     CFileException e;
     CFile* pFile;
     pFile = new CFile;

     for (;;) {
          // Open file for reading and writing; allow others to open for reading only.
          // shareExclusive could be used instead of shareDenyWrite to not allow reading.
          BOOL bResult = pFile->Open(_T("global.txt"),
               CFile::modeReadWrite | CFile::shareDenyWrite, &e);
          if (bResult == FALSE && e.m_cause == CFile::sharingViolation) {
               // sharingViolation is returned if someone else already
               // has the file open.
          else if (bResult == FALSE) {
               // some other error occurred trying to open the file
          else {
               // Success
               // Do Stuff
     delete pFile;
     pFile = NULL;
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.