Menu Home

linux c 单例执行程序

保证系统种某个进程只有一个实例在运行,举例下面2种方法:
1. 使用popen执行ps -ef 后分析结果
2. 使用文件锁
代码如下:

第一种:
int exist(void){
    FILE* fp;
    char buf[10] = {0};
    char command[100] = {0};
    sprintf(command, "ps -ef | grep %s | grep -v grep | wc -l", argv[0]);
    printf("command : %s\n", command);
    fp = popen(command, "r");
    if(fp == NULL)
    {
        perror("popen error!");
        return -1;
    }
    if((fgets(buf, 10, fp))!= NULL)
    {
        if(atoi(buf) != 0)
        {
            printf("%s is running!", argv[0]);
        }
        else
        {
            printf("%s is not running!", argv[0]);
        }
    }
    pclose(fp);
    return 0;
}
第二种
#define LOCKFILE  "/var/run/lte8718wdt.pid"
#define LOCKMODE  (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

int lockfile(int fd)
{
    struct flock fl;
    int ret;

    fl.l_type = F_WRLCK;
    fl.l_start = 0;
    fl.l_whence = SEEK_SET;
    fl.l_len = 0; // lock the whole file

    ret = fcntl(fd, F_SETLK, &fl);
    if(-1 == ret)
        perror("set file lock error!");
    return ret;
}
int is_running(const char* filename)
{
    int fd;
    char pid[15] = {0};

    fd = open(filename, O_RDWR | O_CREAT, LOCKMODE);
    if(fd < 0)
    {
        perror("open file error!");
        return -1;
    }
    if(lockfile(fd) == -1)
    {
        if(errno == EACCES || errno == EAGAIN)
        {
            printf("%s already locked\n", filename);
            close(fd);
            return -1;
        }
    }
    ftruncate(fd, 0);
    sprintf(pid, "%ld", (long)getpid());
    write(fd, pid, sizeof(pid) - 1);
    return 0;
}

Leave a Reply

Your email address will not be published.