Unix/Linux 只有一个进程实例

11 篇文章 0 订阅
9 篇文章 0 订阅

如何保证, Unix/Linux 只有一个进程实例

1. python 实现-文件锁.

#!/usr/bin/env python  
#coding=utf-8  
import fcntl, sys, time  
pidfile = 0  
  
def ApplicationInstance(profile_lock="/var/tmp/instance.lock"):  
    global pidfile  
    pidfile = open(profile_lock, "w")  
    try:  
        fcntl.lockf(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB) #创建一个排他锁,并且所被锁住其他进程不会阻塞
    except  IOError:  
        print "another instance is running..."  
        sys.exit(0)

if __name__ == "__main__":  
    ApplicationInstance()
    while True:
        print 'running...'  
        time.sleep(1)

2. C 实现-文件锁.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/file.h>
#include <unistd.h>


static int g_single_proc_inst_lock_fd = -1; 

static void single_proc_inst_lockfile_cleanup(void)
{
    if (g_single_proc_inst_lock_fd != -1) {
        close(g_single_proc_inst_lock_fd);
        g_single_proc_inst_lock_fd = -1; 
    }   
}

int is_single_proc_inst_running(const char *process_name)
{
    char lock_file[128];
    snprintf(lock_file, sizeof(lock_file), "/var/tmp/%s.lock", process_name);

    g_single_proc_inst_lock_fd = open(lock_file, O_CREAT|O_RDWR, 0644);
    if (-1 == g_single_proc_inst_lock_fd) {
        fprintf(stderr, "Fail to open lock file(%s). Error: %s\n",
        lock_file, strerror(errno));
        return 0;
    }   

    if (0 == flock(g_single_proc_inst_lock_fd, LOCK_EX | LOCK_NB)) {
            atexit(single_proc_inst_lockfile_cleanup);
            return 1;
    }   

    close(g_single_proc_inst_lock_fd);
    g_single_proc_inst_lock_fd = -1; 
    return 0;
}


int main(void)
{
    printf("---run--\n");
    if (is_single_proc_inst_running("process_mcos_client") == 0){
        printf("已经运行!\n");
    }else{
        printf("---启动运行---\n");
    }
    while(1){
        // test         
    }
}

3. QT 实现 -共享内存,放在main 函数即可

int main(int argc, char **argv) 
{
    QApplication app(argc, argv);

    QSharedMemory shared("test_gui"); //随便填个名字就行
    if (shared.attach()) {
         qDebug() << "The program is already running!!!";
        return 0;
    }
    shared.create(1);

    QMainWindow w();
    w.show()

    app.exec();
    shared.detach();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值