• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 316
  • Last Modified:

Locking a File

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
0
Intern
Asked:
Intern
  • 3
  • 2
  • 2
  • +2
1 Solution
 
AlexFMCommented:
Open file in exclusive mode.
0
 
InternAuthor Commented:
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
0
 
imladrisCommented:
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:

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

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
GJanuszCommented:
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() {

}
0
 
GJanuszCommented:
Sorry, I discovered that TAB then SPACE posts my comments!

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.  I tested most of this code.

MyFileMgr::Open()
{
      CFileException e;
      CFile* pFile;
      pFile = new CFile;
      // 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
            pFile->Close();
      }
      delete pFile;
      pFile = NULL;
}

Good Luck!
0
 
itsmeandnobodyelseCommented:
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:
            try
            {
                        // Write to the database.
            }

            finally
            {
               if (! ReleaseMutex(hMutex))
               {
                        // Deal with error.
               }

            break;
            }

                        // 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



0
 
InternAuthor Commented:
>>GJanusz

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.
0
 
itsmeandnobodyelseCommented:
Try

   Sleep(10);

That will wait 10 milliseconds.

Regards, Alex

0
 
GJanuszCommented:
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):

MyFileMgr::Open()
{
     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.
               Sleep(75);
               continue;
          }
          else if (bResult == FALSE) {
               // some other error occurred trying to open the file
          }
          else {
               // Success
               // Do Stuff
               pFile->Close();
          }
          break;
     }
     delete pFile;
     pFile = NULL;
}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now