Unix/Linux 只有一个进程实例

2016-12-02 12:52:55来源:网络收集作者:三线码农人点击

如何保证, 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) #创建一个排他锁,并且所被锁住其他进程不会阻塞
exceptIOError:
print "another instance is running..."
sys.exit(0)
if __name__ == "__main__":
ApplicationInstance()
while True:
print 'running...'
time.sleep(1)
2.C 实现
#include
#include
#include
#include
#include
#include
#include
#include
#include
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
}
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台