singleton.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <sys/file.h>
  5. #include <unistd.h>
  6. #include "singleton.h"
  7. static int g_fdPid = -1;
  8. int AcquirePidFileLock(const char *pszProcessName, const char *pszPidFile)
  9. {
  10. int nRet, nRead, fdPid;
  11. if(g_fdPid >= 0)
  12. {
  13. printf("\n%s: Pidfile lock already acquired!\n\n", pszProcessName);
  14. return 1;
  15. }
  16. fdPid = open(pszPidFile, O_CREAT | O_RDWR, 0666);
  17. if(fdPid < 0)
  18. {
  19. printf("Failed to open PID file: %s\n", pszPidFile);
  20. printf("error: %d\n", errno);
  21. return 0;
  22. }
  23. if((nRet = flock(fdPid, LOCK_EX | LOCK_NB)))
  24. {
  25. if(errno == EWOULDBLOCK)
  26. {
  27. char szPid[32];
  28. if((nRead = (int)read(fdPid, szPid, sizeof(szPid) - 1)) > 0)
  29. {
  30. szPid[nRead] = '\0';
  31. printf("\n%s: another instance is already running -> PID: %s\n\n", pszProcessName, szPid);
  32. }
  33. else
  34. printf("\n%s: another instance is already running!\n\n", pszProcessName);
  35. close(fdPid);
  36. return 0;
  37. }
  38. else
  39. {
  40. printf("flock failed with code %d\n", errno);
  41. close(fdPid);
  42. return 0;
  43. }
  44. }
  45. else
  46. {
  47. char szPid[32];
  48. int nLen = sprintf(szPid, "%d", getpid());
  49. write(fdPid, szPid, (size_t)nLen);
  50. g_fdPid = fdPid;
  51. }
  52. return 1;
  53. }
  54. void ReleasePidFileLock(void)
  55. {
  56. if(g_fdPid >= 0)
  57. {
  58. int fdPid = g_fdPid;
  59. g_fdPid = -1;
  60. flock(fdPid, LOCK_UN);
  61. close(fdPid);
  62. }
  63. }
  64. int GetPidFilePID(const char *pszPidFile)
  65. {
  66. int nRet = -1;
  67. char szPid[32];
  68. ssize_t nRead;
  69. int fdPid = open(pszPidFile, O_RDONLY, 0666);
  70. if(fdPid >= 0)
  71. {
  72. if((nRead = read(fdPid, szPid, sizeof(szPid) - 1)) > 0)
  73. {
  74. szPid[nRead] = '\0';
  75. nRet = atoi(szPid);
  76. }
  77. close(fdPid);
  78. }
  79. return nRet;
  80. }