Electroneum
tools::file_locker Class Reference

#include <util.h>

Public Member Functions

 file_locker (const std::string &filename)
 
 ~file_locker ()
 
bool locked () const
 

Detailed Description

Definition at line 95 of file util.h.

Constructor & Destructor Documentation

◆ file_locker()

tools::file_locker::file_locker ( const std::string &  filename)

Definition at line 238 of file util.cpp.

239  {
240 #ifdef WIN32
241  m_fd = INVALID_HANDLE_VALUE;
242  std::wstring filename_wide;
243  try
244  {
245  filename_wide = string_tools::utf8_to_utf16(filename);
246  }
247  catch (const std::exception &e)
248  {
249  MERROR("Failed to convert path \"" << filename << "\" to UTF-16: " << e.what());
250  return;
251  }
252  m_fd = CreateFileW(filename_wide.c_str(), GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
253  if (m_fd != INVALID_HANDLE_VALUE)
254  {
255  OVERLAPPED ov;
256  memset(&ov, 0, sizeof(ov));
257  if (!LockFileEx(m_fd, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ov))
258  {
259  MERROR("Failed to lock " << filename << ": " << std::error_code(GetLastError(), std::system_category()));
260  CloseHandle(m_fd);
261  m_fd = INVALID_HANDLE_VALUE;
262  }
263  }
264  else
265  {
266  MERROR("Failed to open " << filename << ": " << std::error_code(GetLastError(), std::system_category()));
267  }
268 #else
269  m_fd = open(filename.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
270  if (m_fd != -1)
271  {
272  if (flock_exnb(m_fd) == -1)
273  {
274  MERROR("Failed to lock " << filename << ": " << std::strerror(errno));
275  close(m_fd);
276  m_fd = -1;
277  }
278  }
279  else
280  {
281  MERROR("Failed to open " << filename << ": " << std::strerror(errno));
282  }
283 #endif
284  }
#define MERROR(x)
Definition: misc_log_ex.h:73
::std::wstring wstring
Definition: gtest-port.h:1103

◆ ~file_locker()

tools::file_locker::~file_locker ( )

Definition at line 285 of file util.cpp.

286  {
287  if (locked())
288  {
289 #ifdef WIN32
290  CloseHandle(m_fd);
291 #else
292  close(m_fd);
293 #endif
294  }
295  }
bool locked() const
Definition: util.cpp:296

Member Function Documentation

◆ locked()

bool tools::file_locker::locked ( ) const

Definition at line 296 of file util.cpp.

297  {
298 #ifdef WIN32
299  return m_fd != INVALID_HANDLE_VALUE;
300 #else
301  return m_fd != -1;
302 #endif
303  }

The documentation for this class was generated from the following files: