Kea  1.9.9-git
pid_file.cc
Go to the documentation of this file.
1 // Copyright (C) 2015 Internet Systems Consortium, Inc. ("ISC")
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 
7 #include <config.h>
8 
9 #include <util/pid_file.h>
10 #include <cstdio>
11 #include <signal.h>
12 #include <unistd.h>
13 #include <cerrno>
14 
15 namespace isc {
16 namespace util {
17 
18 PIDFile::PIDFile(const std::string& filename)
19  : filename_(filename) {
20 }
21 
23 }
24 
25 int
26 PIDFile::check() const {
27  std::ifstream fs(filename_.c_str());
28  int pid;
29  bool good;
30 
31  // If we weren't able to open the file treat
32  // it as if the process wasn't running
33  if (!fs.is_open()) {
34  return (false);
35  }
36 
37  // Try to get the pid, get the status and get rid of the file
38  fs >> pid;
39  good = fs.good();
40  fs.close();
41 
42  // If we weren't able to read a pid send back an exception
43  if (!good) {
44  isc_throw(PIDCantReadPID, "Unable to read PID from file '"
45  << filename_ << "'");
46  }
47 
48  // If the process is still running return its pid.
49  if (kill(pid, 0) == 0) {
50  return (pid);
51  }
52 
53  // No process
54  return (0);
55 }
56 
57 void
58 PIDFile::write() const {
59  write(getpid());
60 }
61 
62 void
63 PIDFile::write(int pid) const {
64  std::ofstream fs(filename_.c_str(), std::ofstream::trunc);
65 
66  if (!fs.is_open()) {
67  isc_throw(PIDFileError, "Unable to open PID file '"
68  << filename_ << "' for write");
69  }
70 
71  // File is open, write the pid.
72  fs << pid << std::endl;
73 
74  bool good = fs.good();
75  fs.close();
76 
77  if (!good) {
78  isc_throw(PIDFileError, "Unable to write to PID file '"
79  << filename_ << "'");
80  }
81 }
82 
83 void
85  if ((remove(filename_.c_str()) != 0) &&
86  (errno != ENOENT)) {
87  isc_throw(PIDFileError, "Unable to delete PID file '"
88  << filename_ << "'");
89  }
90 }
91 
92 } // namespace isc::util
93 } // namespace isc
void deleteFile() const
Delete the PID file.
Definition: pid_file.cc:84
int check() const
Read the PID in from the file and check it.
Definition: pid_file.cc:26
Exception thrown when an error occurs during PID file processing.
Definition: pid_file.h:20
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
void write() const
Get PID of the current process and write it to the file.
Definition: pid_file.cc:58
Defines the logger used by the top-level component of kea-dhcp-ddns.
PIDFile(const std::string &filename)
Constructor.
Definition: pid_file.cc:18
~PIDFile()
Destructor.
Definition: pid_file.cc:22
Exception thrown when an error occurs trying to read a PID from an opened file.
Definition: pid_file.h:28