c++ - Interogate which process has locked a file in Windows C ++ -
i have 2 applications sharing same lock file, , need know when the other application has either locked/unlocked file. code below implemented on linux machine, , being ported window 8, vs12.
i have ported other code in class , locking files lockfile(handle, 0, 0, sizeof(int), 0) , equivalent unlockfile(...). however, having trouble following wait() command.
bool devices::comms::cdevicefilelock::wait(bool locked, int timeout) { // retrieve current pid of process. pid_t pid = getpid(); // determine if tracking time. bool tracking = (timeout > 0); // retrieve lock information. struct flock lock; if (fcntl(m_ilockfile, f_getlk, &lock) != 0) raiseexception("failed retrieve lock file information"); // loop until state changes. time_t timenow = time(null); while ((pid == lock.l_pid) && (lock.l_type != (locked ? f_wrlck : f_unlck))) { // retrieve lock information. if (fcntl(m_ilockfile, f_getlk, &lock) != 0) raiseexception("failed retrieve lock file information"); // check timeout, if tracking. if (tracking) { time_t timecheck = time(null); if (difftime(timenow, timecheck) > timeout) return false; } } // return success. return true; }
note: m_ilockfile used file descriptor open(), called m_hlockfile , handle createfile().
i cannot seem find windows equivalent of fcntl f_getlk command. know if can either: a) use fcntl equivalent interrogate locking information, find out process has obtained lock b) suggest how above can re-written windows c++.
note: server application using lock file standalone c++ executable, client using lock file winrt windows application. suggested solution cannot break sandboxing of client.
thanks.
you not going find in windows, fundamentally unsound on multi-tasking operating system. value you'd isfilelocked() api function meaningless, process or thread still lock file microsecond later.
the workaround simple, if need lock try acquire one. if file locked lockfile() return false, getlasterror() tells why. atomic, essential property of lock. if can afford wait lock use lockfileex() without lockfile_fail_immediately option.
Comments
Post a Comment