Unix/Linux 只有一个进程实例

来源:互联网 发布:git linux 安装 编辑:程序博客网 时间:2024/06/07 13:36

如何保证, 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             }}
0 0
原创粉丝点击