首页 > 代码库 > linux:如何防止程序开启两个实例(进程)?

linux:如何防止程序开启两个实例(进程)?

有时候不小心开启同一个程序两次会造成意想不到的错误,下面介绍一种方法,可以防止出现这种情况,测试可用。

在程序中添加如下代码

 1 #include <unistd.h> 2 #include <signal.h> 3 #include <sys/types.h> 4 #include <sys/stat.h> 5 #include <errno.h> 6 #include <fcntl.h> 7 #include <fstream> 8  9 10 #define PIDFILE     "/daemon_shouhu.pid"         //定义你自己的file名11 #define    write_lock(fd, offset, whence, len) 12     lock_reg(fd, F_SETLK, F_WRLCK, offset, whence, len)13 14 int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)15 {16     struct flock    lock;17 18     lock.l_type = type;        /* F_RDLCK, F_WRLCK, F_UNLCK */19     lock.l_start = offset;        /* byte offset, relative to l_whence */20     lock.l_whence = whence;        /* SEEK_SET, SEEK_CUR, SEEK_END */21     lock.l_len = len;        /* #bytes (0 means to EOF) */22 23     return( fcntl(fd, cmd, &lock) );    /* -1 upon error */24 }25 26 27 28 int Check_Running()29 {30     int fd, val;   31 32     if ((fd = open(PIDFILE, O_WRONLY|O_CREAT, "at")) < 0)33     {34         printf(" Open file error \n");35     }36 37     if (write_lock(fd, 0, SEEK_SET, 0) < 0)38     { 39         if (errno == EACCES || errno == EAGAIN)40         {41             printf(" Server Already running! \n");42             _exit(-1);43             return -1;44         }45         else46         {47             printf(" Write_lock error! \n");48         }49     }50 51     if (ftruncate(fd, 0) < 0)52     {53         printf("  ftruncate error  \n");    54     }55 56     char buf[10] = {0};57     sprintf(buf, "%d\n", getpid());58     if (write(fd, buf, strlen(buf)) != (int)strlen(buf))59         printf(" Write error \n"); 60 61     if ((val = fcntl(fd, F_GETFD, 0)) < 0)62         printf(" fcntl F_GETFD error \n");63 64     val |= FD_CLOEXEC;65     if (fcntl(fd, F_SETFD, val) < 0)66         printf(" fcntl F_SETFD error \n");67 68     return 0;69 }

然后在程序入口添加Check_Running()就可以了,重新编译后执行,当第二次打开程序时会输出" Server Already running! ",第二个进程无法打开。