保证某一执行文件只有一个实例在运行

来源:互联网 发布:录音机软件 手机 编辑:程序博客网 时间:2024/05/18 04:05

1.启动进程后,先检查pid文件是否存在,存在则读取之前写入的pid,然后用上面的kill(pid,0);来检查是否活着,
2.活着则退出进程,不允许再启动一个进程,否则启动并将当前的pid写入pid文件。写入的时候要锁住文件,避免其他进程也往里面写,主要是lockf这个系统调用

 

void writePidFile(const char *szPidFile)  {      /*open the file*/      char            str[32];      int lfp = open(szPidFile, O_WRONLY|O_CREAT|O_TRUNC, 0600);      if (lfp < 0) exit(1);        /*F_LOCK(block&lock) F_TLOCK(try&lock) F_ULOCK(unlock) F_TEST(will not lock)*/      if (lockf(lfp, F_TLOCK, 0) < 0) {          fprintf(stderr, "Can't Open Pid File: %s", szPidFile);          exit(0);      }        /*get the pid,and write it to the pid file.*/      sprintf(str, "%d\n", getpid()); // \n is a symbol.       ssize_t len = strlen(str);      ssize_t ret = write(lfp, str, len);      if (ret != len ) {          fprintf(stderr, "Can't Write Pid File: %s", szPidFile);          exit(0);      }      close(lfp);  }


int existPid(const char *szPidFile)

{

      读取该文件中的pid

      if(pid > 0){

            if(kill (pid,0) != 0){

                    pid = 0;

            }

      }

      return pid;

}

0 0
原创粉丝点击