如何保证, Unix/Linux 只有一个进程实例
1. python 实现-文件锁.
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){
}
}
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;
}