#include #include #include #include #include #include "singleton.h" static int g_fdPid = -1; int AcquirePidFileLock(const char *pszProcessName, const char *pszPidFile) { int nRet, nRead, fdPid; if(g_fdPid >= 0) { printf("\n%s: Pidfile lock already acquired!\n\n", pszProcessName); return 1; } fdPid = open(pszPidFile, O_CREAT | O_RDWR, 0666); if(fdPid < 0) { printf("Failed to open PID file: %s\n", pszPidFile); printf("error: %d\n", errno); return 0; } if((nRet = flock(fdPid, LOCK_EX | LOCK_NB))) { if(errno == EWOULDBLOCK) { char szPid[32]; if((nRead = (int)read(fdPid, szPid, sizeof(szPid) - 1)) > 0) { szPid[nRead] = '\0'; printf("\n%s: another instance is already running -> PID: %s\n\n", pszProcessName, szPid); } else printf("\n%s: another instance is already running!\n\n", pszProcessName); close(fdPid); return 0; } else { printf("flock failed with code %d\n", errno); close(fdPid); return 0; } } else { char szPid[32]; int nLen = sprintf(szPid, "%d", getpid()); write(fdPid, szPid, (size_t)nLen); g_fdPid = fdPid; } return 1; } void ReleasePidFileLock(void) { if(g_fdPid >= 0) { int fdPid = g_fdPid; g_fdPid = -1; flock(fdPid, LOCK_UN); close(fdPid); } } int GetPidFilePID(const char *pszPidFile) { int nRet = -1; char szPid[32]; ssize_t nRead; int fdPid = open(pszPidFile, O_RDONLY, 0666); if(fdPid >= 0) { if((nRead = read(fdPid, szPid, sizeof(szPid) - 1)) > 0) { szPid[nRead] = '\0'; nRet = atoi(szPid); } close(fdPid); } return nRet; }