single_instance.c 3.3 KB

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