lockFile.cpp
Go to the documentation of this file.00001
00015 #include <limits>
00016 #include <sys/types.h>
00017 #include <sys/stat.h>
00018 #include <fcntl.h>
00019 #include <dlrUtilities/lockFile.h>
00020 #include <dlrUtilities/timeUtilities.h>
00021
00022 namespace dlr {
00023
00024 namespace utilities {
00025
00026
00027 LockFile::
00028 LockFile(const std::string& fileName,
00029 double timeout)
00030 : m_fileDescriptor(open(fileName.c_str(), O_WRONLY | O_CREAT | O_EXCL,
00031 S_IRUSR)),
00032 m_fileName(fileName)
00033 {
00034 if(timeout != 0.0) {
00035 double stopTime = std::numeric_limits<double>::max();
00036 double sleepTime = 0.1;
00037 if(timeout > 0.0) {
00038 stopTime = getCurrentTime() + timeout;
00039 sleepTime = std::min(1.0, timeout / 100.0);
00040 }
00041 while(m_fileDescriptor < 0) {
00042 portableSleep(sleepTime);
00043 m_fileDescriptor =
00044 open(fileName.c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR);
00045 if(getCurrentTime() > stopTime) {
00046 break;
00047 }
00048 }
00049 }
00050 if(m_fileDescriptor != -1) {
00051 close(m_fileDescriptor);
00052 }
00053 }
00054
00055
00056
00057 LockFile::
00058 LockFile(const std::string& fileName,
00059 const std::string& contents,
00060 double timeout)
00061 : m_fileDescriptor(open(fileName.c_str(), O_WRONLY | O_CREAT | O_EXCL,
00062 S_IWUSR)),
00063 m_fileName(fileName)
00064 {
00065 if(timeout != 0.0) {
00066 double stopTime = std::numeric_limits<double>::max();
00067 double sleepTime = 0.1;
00068 if(timeout > 0.0) {
00069 stopTime = getCurrentTime() + timeout;
00070 sleepTime = std::min(1.0, timeout / 100.0);
00071 }
00072 while(m_fileDescriptor < 0) {
00073 portableSleep(sleepTime);
00074 m_fileDescriptor =
00075 open(fileName.c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR);
00076 if(getCurrentTime() > stopTime) {
00077 break;
00078 }
00079 }
00080 }
00081 if(m_fileDescriptor != -1) {
00082
00083 write(m_fileDescriptor, (const void*)contents.c_str(), contents.size());
00084 close(m_fileDescriptor);
00085 chmod(m_fileName.c_str(), S_IRUSR);
00086 }
00087 }
00088
00089
00090
00091
00092 LockFile::
00093 ~LockFile()
00094 {
00095 if(m_fileDescriptor != -1) {
00096
00097
00098
00099 chmod(m_fileName.c_str(), S_IWUSR);
00100 unlink(m_fileName.c_str());
00101 }
00102 }
00103
00104
00105
00106
00107 bool
00108 LockFile::
00109 isValid()
00110 {
00111 return (m_fileDescriptor != -1);
00112 }
00113
00114 }
00115
00116 }