c++ - 使用 Windows C++ LockFIle() 锁定文件然后从中获取流?

标签 c++ windows visual-c++ locking interprocess

我已经使用 LockFileEx 锁定了一个文件,但我无法打开其中的流。

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;    
   }
}

获取锁后,我想这样做:

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;
}

我这样做是因为我发现使用流逐行阅读更容易...

有解决办法吗?

最佳答案

来自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.

因此您需要使用已有的句柄,而不是创建一个新句柄。

_open_osfhandle函数允许您从现有句柄创建文件描述符,然后您可以将此文件描述符传递给 ofstream constructor而不是文件名。

关于c++ - 使用 Windows C++ LockFIle() 锁定文件然后从中获取流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24664046/

相关文章:

ruby - 如何确定 Ruby 中路径或文件的文件系统?

c++ - Visual C++ 中的二进制再现性

c++ - 从可变参数模板类中特化一个函数

C++ 如何比较类

c++ - 如何在现代 C++ 中使用分配器

windows - 如何在 Windows 中获取窗口的默认标题栏高度?

Windows 控制台上的 C 可选输入

windows - PE文件格式中的基址重定位表是什么?

c - 如何在 MSVC 上通过 socket() 创建套接字?

c++ - 静态数据成员是否在所有类对象之前初始化?