【发布时间】:2013-07-17 05:13:34
【问题描述】:
我有 2 个应用程序共享同一个锁定文件,我需要知道何时 另一个应用程序已锁定/解锁文件。下面的代码是 最初是在 Linux 机器上实现的,现在正在移植到 Window 8,VS12。
我已经成功移植了类中的所有其他代码,并且正在锁定文件 LockFile(handle, 0, 0, sizeof(int), 0) 和等效的 UnlockFile(...)。然而, 我在使用以下 wait() 命令时遇到问题。
bool devices::comms::CDeviceFileLock::wait(bool locked,
int timeout)
{
// Retrieve the current pid of the process.
pid_t pid = getpid();
// Determine if we are tracking time.
bool tracking = (timeout > 0);
// Retrieve the lock information.
struct flock lock;
if (fcntl(m_iLockFile, F_GETLK, &lock) != 0)
raiseException("Failed to retrieve lock file information");
// Loop until the state changes.
time_t timeNow = time(NULL);
while ((pid == lock.l_pid)
&&
(lock.l_type != (locked ? F_WRLCK : F_UNLCK)))
{
// Retrieve the lock information.
if (fcntl(m_iLockFile, F_GETLK, &lock) != 0)
raiseException("Failed to retrieve lock file information");
// Check for timeout, if we are tracking.
if (tracking)
{
time_t timeCheck = time(NULL);
if (difftime(timeNow, timeCheck) > timeout)
return false;
}
}
// Return success.
return true;
}
注意:m_iLockFile 以前是来自 open() 的文件描述符,现在称为 m_hLockFile 是来自 CreateFile() 的 HANDLE。
我似乎找不到 fcntl F_GETLK 命令的 Windows 等效项。 有谁知道我是否可以: a) 使用 fcntl 等价于询问锁定信息,找出 哪个进程获得了锁 b) 建议如何为 Windows C++ 重写上述内容。
注意:使用锁定文件的服务器应用程序是一个独立的 C++ 可执行文件, 但是使用锁定文件的客户端是 WinRT Windows 应用程序。所以任何 建议的解决方案不能破坏客户端的沙盒。
谢谢。
【问题讨论】: