Search code examples
c++windowsvisual-c++lockinginterprocess

Lock a file using windows c++ LockFIle() then get a stream from it?


I have locked a file using LockFileEx, but I am not able to open a stream from it.

HANDLE indexHandle = CreateFile (indexFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, 
        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

bool indexLock = false;
OVERLAPPED overlapped;
memset (&overlapped, 0, sizeof (overlapped));
while (noOfTries >0 && !indexLock)
{
   if (!LockFileEx (indexHandle, LOCKFILE_EXCLUSIVE_LOCK, 0, 0, UINT_MAX, &overlapped))
   {
      InfoLog << "Failed to get lock on index file  -- Error code is ["
            << GetLastError () <<"]"<<std::endl;
      Sleep(sleepTime);
      noOfTries--;

   }
   else
   {
      indexLock=true;    
   }
}

After the lock is acquired, I want to do this:

string indexFile = mPath + Util::PATH_SEPARATOR + mIndexFileName;
os.open( indexFile.c_str(), ios_base::app);
if (!os)
{
  InfoLog << "BinaryFileSystemObjectStore:: ofstream: Failed to open index for write: " << indexFile.c_str() << endl;
}

I do this because I find it easier to read line by line with streams...

Is there a solution?


Solution

  • From the documentation for LockFileEx:

    If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region.

    So you need to use the handle you already have rather than creating a new one.

    The _open_osfhandle function allows you to create a file descriptor from an existing handle, and you can then pass this file descriptor to the ofstream constructor instead of the filename.