/* The software in this package is distributed under the GNU General Public License version 2 (with a special exception described below). A copy of GNU General Public License (GPL) is included in this distribution, in the file COPYING.GPL. As a special exception, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License. */ /** Pid file handling @copyright Intra2net AG */ #include "pidfile.hpp" #include #include #include #include #include #include #include "filefunc.hxx" #include using namespace std; using namespace I2n; /** * Constructor. * @param filename Full path to the pid file * @param remove_file_on_destruction Remove pid file on destruction of the object. Only useful if running as root. */ PidFile::PidFile(const std::string &filename, bool remove_file_on_destruction) { Filename = filename; RemoveFileOnDestruction = remove_file_on_destruction; WroteFile = false; } /** * Destructor. We delete the pid file if #RemoveFileOnDestruction is set * and we actually wrote a file (#WroteFile). * This is only possible if we run with root priviledges as /var/run * is root writable only. */ PidFile::~PidFile() { if (RemoveFileOnDestruction && WroteFile) unlink(Filename); } /** * Checks if the pid file for this program already exists. * If yes it does a "kill" probe to see if it is alive. * @param running_pid[out] Store pid number of instance if already running * @return true if running, false otherweise */ bool PidFile::check_already_running(pid_t *running_pid) { // Check if there is an existing pid file ifstream in(Filename.c_str()); if (!in) return false; pid_t read_pid = 0; if (!(in >> read_pid)) return false; // Ok, we got an existing pid file. // Check if program is still alive if (kill(read_pid, 0) == 0) { if (running_pid) *running_pid = read_pid; // State: running return true; } // Default state: not running return false; } /** * Write pid file * @return true if file was written, false otherwise */ bool PidFile::write() { ofstream out(Filename.c_str()); if (!out) return false; out << getpid() << endl; WroteFile = true; return true; }