Unix环境产生单实例进程方案


在一些情况下,一个进程只能产生一个实例来执行。Unix环境,提供了文件-记录锁(file- and record-locking)机制,提供了事项单实例进程的基本解决方案。

假如,一个进程在开始运行时,生成了一个文件,并且,对整个文件上锁,并且,只有一个这样的写锁允许生成。

如果,后续的进程要试图产生写锁,会导致失败。这暗示了,前面已经有实例运行了。

下面一个判断是否有实例运行的方法。每个实例,都会试图生成一个文件(/var/run/daemon.pid).如果文件已经锁上了,lockfile方法,返回失败,判断函数返回1,表示进程已经运行了。如果没有实例运行,程序,清空文件,写入进程id,返回0.

下面为一个实现的程序:

  1. #include <unistd.h>   
  2. #include <stdio.h>   
  3. #include <stdlib.h>   
  4. #include <fcntl.h>   
  5. #include <syslog.h>   
  6. #include <string.h>   
  7. #include <errno.h>   
  8. #include <sys/stat.h>   
  9. #define LOCKFILE "/var/run/daemon.pid"   
  10. #define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)   
  11. int already_running(void);   
  12. int lockfile(int );   
  13. int main(int argc,char * argv[])   
  14. {   
  15.     int val = already_running();   
  16.     if(val == 0)   
  17.     {   
  18.         printf("sart to running...\n");   
  19.     }   
  20.     else  
  21.     {   
  22.         printf("alredy running...\n");   
  23.         exit(0);   
  24.     }   
  25.     while(1)   
  26.     {   
  27.         sleep(3);   
  28.         printf("...\n");   
  29.     }   
  30.     return 0;   
  31. }   
  32. int already_running(void)   
  33. {   
  34.     int fd;   
  35.     char buf[16];   
  36.     fd = open(LOCKFILE,O_RDWR|O_CREAT, LOCKMODE);   
  37.     if(fd < 0)   
  38.     {   
  39.         syslog(LOG_ERR, "can't open %s: %s", LOCKFILE, strerror(errno));   
  40.         exit(1);   
  41.     }   
  42.     if(lockfile(fd) < 0)   
  43.     {   
  44.         if (errno == EACCES || errno == EAGAIN)   
  45.         {   
  46.             close(fd);   
  47.             return 1;   
  48.         }   
  49.         syslog(LOG_ERR,"can't lock %s: %s", LOCKFILE, strerror(errno));   
  50.         exit(1);   
  51.     }   
  52.     ftruncate(fd,0);   
  53.     sprintf(buf,"%ld",(long)getpid());   
  54.     write(fd,buf,strlen(buf) + 1);   
  55.     return 0;   
  56. }   
  57. int lockfile(int fd)   
  58. {   
  59.     struct flock fl;   
  60.     fl.l_type = F_WRLCK;   
  61.     fl.l_start = 0;   
  62.     fl.l_whence = SEEK_SET;   
  63.     fl.l_len = 0;   
  64.     return(fcntl(fd, F_SETLK, &fl));   
  65. }  

相关内容