diff --git a/znc.cpp b/znc.cpp index 2d365544..79d49d26 100644 --- a/znc.cpp +++ b/znc.cpp @@ -6,6 +6,7 @@ #include "Utils.h" #include +#include #include #ifdef _MODULES @@ -125,6 +126,46 @@ void CZNC::ReleaseISpoof() { m_bISpoofLocked = false; } +bool CZNC::SetPidFile(const string& sFile) { + CUtils::PrintAction("Checking PidFile [" + sFile + "]"); + + if (!sFile.empty() && sFile[0] != '/') { + m_sPidFile = GetZNCPath() + "/" + sFile; + } else { + m_sPidFile = sFile; + } + + if (!m_sPidFile.empty()) { + unsigned int uPid = 0; + CFile File(m_sPidFile); + + if (File.Open(O_RDONLY)) { + string sPid; + + if (File.ReadLine(sPid)) { + uPid = atoi(sPid.c_str()); + + if (uPid > 0 && kill(uPid, 0) == 0) { + CUtils::PrintStatus(false, "ZNC already running [pid: " + CUtils::ToString(uPid) + "]"); + File.Close(); + + return false; + } else { + CUtils::PrintStatus(true, "Stale pid, relaunching"); + File.Close(); + + return true; + } + } + + File.Close(); + } + } + + CUtils::PrintStatus(true); + return true; +} + bool CZNC::WritePidFile(int iPid) { if (!m_sPidFile.empty()) { CFile File(m_sPidFile); @@ -485,10 +526,10 @@ bool CZNC::ParseConfig(const string& sConfigFile) { m_sISpoofFile = sValue; continue; } else if (strcasecmp(sName.c_str(), "PidFile") == 0) { - if (!sValue.empty() && sValue[0] != '/') { - m_sPidFile = GetZNCPath() + "/" + sValue; - } else { - m_sPidFile = sValue; + if (!sValue.empty()) { + if (!SetPidFile(sValue)) { + return false; + } } continue; diff --git a/znc.h b/znc.h index 76cf2aca..0b19fe37 100644 --- a/znc.h +++ b/znc.h @@ -16,6 +16,7 @@ public: void DeleteUsers(); int Loop(); void ReleaseISpoof(); + bool SetPidFile(const string& sFile); bool WritePidFile(int iPid); CUser* GetUser(const string& sUser); Csock* FindSockByName(const string& sSockName);