/* vim: set ts=4 et sw=4 tw=78 : */
#include <fstream>
+#include <sys/file.h>
+#include <unistd.h>
+#include "dpl/errno_string.h"
#include "dpl/log/log.h"
#include "file-lock.h"
ThrowMsg(FileLocker::Exception::LockFailed,
"File name can not be empty.");
}
-
+ m_lockFileFd = open(lockFile.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
+ if (m_lockFileFd == -1) {
+ LogError("Lock file cannot be opened " << lockFile);
+ ThrowMsg(FileLocker::Exception::LockFailed,
+ "Lock file cannot be opened " << lockFile);
+ }
m_locked = false;
m_blocking = blocking;
m_lockFile = lockFile;
} catch (...) {
LogError("~FileLocker() threw an exception");
}
+ (void)close(m_lockFileFd);
}
bool FileLocker::Locked()
if (m_locked)
return;
- try {
- std::ofstream tmpf(m_lockFile);
- tmpf.close();
-
- m_flock = boost::interprocess::file_lock(m_lockFile.c_str());
- if (m_blocking) {
- m_flock.lock();
- m_locked = true;
- } else
- m_locked = m_flock.try_lock();
- } catch (const std::exception &e) {
- LogError("Error while locking a file: " << e.what());
+ int ret;
+ while((-1 == (ret = flock(m_lockFileFd, m_blocking ? LOCK_EX : LOCK_NB | LOCK_EX))) && (errno == EINTR));
+ m_locked = ret == 0;
+ int err = errno;
+ if (-1 == ret && err != EWOULDBLOCK) {
+ LogError("Error while locking a file " << m_lockFile);
ThrowMsg(FileLocker::Exception::LockFailed,
- "Error while locking a file: " << e.what());
+ "Error while locking a file " << m_lockFile << ", error: " << GetErrnoString(err));
}
if (m_locked)
void FileLocker::Unlock()
{
if (m_locked) {
- try {
- m_flock.unlock();
- } catch (const std::exception &e) {
- LogError("Error while unlocking a file: " << e.what());
+ int ret;
+ while((-1 == (ret = flock(m_lockFileFd, LOCK_UN))) && (errno == EINTR));
+ if (-1 == ret) {
+ int err = errno;
+ LogError("Error while unlocking a file " << m_lockFile);
ThrowMsg(FileLocker::Exception::UnlockFailed,
- "Error while unlocking a file: " << e.what());
+ "Error while unlocking a file " << m_lockFile << ", error: " << GetErrnoString(err));
}
m_locked = false;
LogDebug("Lock released.");