00001 #ifndef _sys_posix_LockFile_h
00002 #define _sys_posix_LockFile_h
00003
00004 #include "check.h"
00005
00006 #include <boost/noncopyable.hpp>
00007 #include <string>
00008 #include <unistd.h>
00009 #include <sys/types.h>
00010 #include <sys/stat.h>
00011 #include <fcntl.h>
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 namespace qpid {
00031 namespace sys {
00032
00033 class LockFile : private boost::noncopyable {
00034 public:
00035 LockFile(const std::string& path_, bool create):
00036 path(path_), fd(-1), created(create) {
00037 errno = 0;
00038 int flags=create ? O_WRONLY|O_CREAT|O_NOFOLLOW : O_RDWR;
00039 fd = ::open(path.c_str(), flags, 0644);
00040 if (fd < 0) throw ErrnoException("Cannot open " + path, errno);
00041 if (::lockf(fd, F_TLOCK, 0) < 0) throw ErrnoException("Cannot lock " + path, errno);
00042 }
00043
00044 ~LockFile() {
00045 if (fd >= 0) {
00046 (void) ::lockf(fd, F_ULOCK, 0);
00047 ::close(fd);
00048 }
00049 }
00050
00051 std::string path;
00052 int fd;
00053 bool created;
00054 };
00055
00056 }
00057 }
00058 #endif