#include <fcntl.h>

namespace file_tools {

class LockFile {
   int fd;
   const char * file_name;

public:
   LockFile(const char * fn) 
   {
      file_name = fn;
      fd = open(fn, O_EXCL | O_RDWR);
   }

   ~LockFile()
   {
      close(fd);
   }

   void read_lock();
   void read_unlock();
   void write_lock();
   void write_unlock();
   operator void*() { return ((void*)(fd > 0)); }
};

inline
void
LockFile::read_lock()
{
   flock(fd, LOCK_SH);
}

inline
void
LockFile::read_unlock()
{
   flock(fd, LOCK_UN);
}

inline
void
LockFile::write_lock()
{
   flock(fd, LOCK_EX);
}

inline
void
LockFile::write_unlock()
{
   flock(fd, LOCK_UN);
}

}
