commSingleApp.c 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**************************************************************************************************
  2. ** **
  3. ** 文件名称: commSingleApp.c **
  4. ** 版权所有: CopyRight @ LEON WorkStudio CO.LTD. 2017 **
  5. ** 文件描述: 判断系统中是否已经存在该进程的实例 **
  6. ** =========================================================================================== **
  7. ** 创建信息: | 2017-9-14 | LEON | 创建本模块 **
  8. ** =========================================================================================== **
  9. ** 修改信息: 单击此处添加.... **
  10. **************************************************************************************************/
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <unistd.h>
  14. #include <fcntl.h>
  15. #include <printf.h>
  16. #include <string.h>
  17. #include <errno.h>
  18. #include <sys/stat.h>
  19. #include "commSingleApp.h"
  20. /**************************************************************************************************
  21. ** 函数名称: lockfile
  22. ** 功能描述: 对文件加锁
  23. ** 输入参数: 无
  24. ** 输出参数: 无
  25. ** 返回参数: 无
  26. **************************************************************************************************/
  27. static int lockfile(int fd)
  28. {
  29. struct flock fl;
  30. fl.l_type = F_WRLCK;
  31. fl.l_start = 0;
  32. fl.l_whence = SEEK_SET;
  33. fl.l_len = 0;
  34. return(fcntl(fd, F_SETLK, &fl));
  35. }
  36. /**************************************************************************************************
  37. ** 函数名称: proc_is_exist
  38. ** 功能描述: 判断系统中是否存在该进程
  39. ** 输入参数: procname: 进程名
  40. ** 输出参数: 无
  41. ** 返回参数: 返回1表示系统中已经存在该进程了;返回0表示系统中不存在该进程
  42. ** 注意事项: 此处加锁完后无需对文件进行close,而是进程退出后由系统来释放;否则无法起到保护的作用
  43. **************************************************************************************************/
  44. int proc_is_exist(const char *procname)
  45. {
  46. int fd;
  47. char buf[16];
  48. char filename[100];
  49. sprintf(filename, "/var/run/%s.pid", procname);
  50. fd = open(filename, O_RDWR | O_CREAT, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
  51. if (fd < 0) {
  52. printf("open file \"%s\" failed!!!\n", filename);
  53. return 1;
  54. }
  55. if (lockfile(fd) == -1) { /* 尝试对文件进行加锁 */
  56. printf("file \"%s\" locked. proc already exit!!!\n", filename);
  57. close(fd);
  58. return 1;
  59. } else {
  60. ftruncate(fd, 0); /* 写入运行实例的pid */
  61. sprintf(buf, "%ld", (long)getpid());
  62. write(fd, buf, strlen(buf) + 1);
  63. return 0;
  64. }
  65. }
  66. #if 0 //测试
  67. if (proc_is_exist(g_fk_process_name) == TRUE) { /* 单实例运行 */
  68. print_sys("an \"%s\" already running in system. exit now...\n", g_fk_process_name);
  69. return 0;
  70. } else {
  71. print_sys("\"%s\" starting...\n", g_fk_process_name);
  72. }
  73. #endif