9 static const char rcsid[] __attribute__((used)) =
"$Id: PidFile.cpp 1653 2016-02-28 19:54:59Z sella $";
21 using namespace sella::util;
23 PidFile::PidFile(
const std::string &file, uid_t uid, gid_t gid)
throw () : file(file), uid(uid), gid(gid) {
24 assert(!file.empty());
27 PidFile::PidFile(
const PidFile &other) : file(other.file), uid(other.uid), gid(other.gid) {
35 this->file = other.file;
36 this->uid = other.uid;
37 this->gid = other.gid;
43 const std::string& PidFile::get(
void)
const throw () {
47 int PidFile::read(
void)
const throw (PidFileException) {
51 if ((h = fopen(file.c_str(),
"r")) == NULL) {
52 THROW(PidFileException,
"Failed to open file '%s'", file.c_str());
55 if (fscanf(h,
"%d", &pid) == EOF) {
56 THROW(PidFileException,
"Failed to read file '%s'", file.c_str());
64 int PidFile::write(
void)
const throw (PidFileException) {
68 if ((fd = open(file.c_str(), O_RDWR|O_CREAT, 0644)) == -1 || (h = fdopen(fd,
"r+")) == NULL) {
69 THROW(PidFileException,
"Failed to open or create file '%s'", file.c_str());
72 if (flock(fd, LOCK_EX|LOCK_NB) == -1) {
73 if (fscanf(h,
"%d", &pid) == EOF) {
78 THROW(PidFileException,
"Lock on file '%s' is already held by pid %d", file.c_str(), pid);
83 if (fprintf(h,
"%d\n", pid) < 1) {
86 THROW2(PidFileException,
"Failed to write pid %d to file '%s'", pid, file.c_str());
91 if (flock(fd, LOCK_UN) == -1) {
92 THROW2(PidFileException,
"Failed to unlock file '%s'", file.c_str());
95 if (uid != (__UID_T_TYPE) -1 || gid != (__GID_T_TYPE) -1) {
96 if (fchown(fd, uid, gid) != 0) {
97 THROW2(PidFileException,
"Failed to change owner of file '%s' to %d:%d", file.c_str(), uid, gid);
106 void PidFile::remove(
void)
const throw (PidFileException) {
107 if (unlink(file.c_str()) != 0) {
108 THROW2(PidFileException,
"Failed to remove file '%s'", file.c_str());
112 bool PidFile::isOwner(
void)
const throw () {
117 }
catch (PidFileException) {
121 return (pid == getpid());
124 bool PidFile::isLive(
void)
const throw () {
129 }
catch (PidFileException) {
133 if (pid == getpid()) {
138 if (pid == 0 || (kill(pid, 0) != 0 && errno == ESRCH)) {
145 bool PidFile::isFile(
void)
const throw () {
148 if ((h = fopen(file.c_str(),
"r")) == NULL) {
157 const PidFile::shared PidFile::shared_ptr(
const std::string &file, uid_t uid, gid_t gid)
throw () {
158 return std::make_shared<PidFile>(file, uid, gid);