linux实现程序唯一性

在Linux下确保程序唯一运行的方法有很多,以下是一种常见的方法,使用文件锁(也称为互斥锁)。

你可以使用 fcntl 库中的 flock 函数来创建一个锁文件。如果程序已经运行,尝试创建同一个锁文件将失败,你可以通过检查这个失败来确定程序是否已在运行。

以下是一个简单的C++示例代码,展示了如何使用 flock 来确保程序的唯一运行:(网上找到的,未验证,有机会待验证)

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
int lock_fd = open("/tmp/myapp.lock", O_CREAT | O_EXCL | O_RDWR, 0666);
if (lock_fd == -1) {
perror("open");
printf("Another instance of the application is running.\n");
exit(EXIT_FAILURE);
}

// 加锁,防止其他进程获取锁
if (flock(lock_fd, LOCK_EX | LOCK_NB) == -1) {
perror("flock");
close(lock_fd);
exit(EXIT_FAILURE);
}

// 程序主逻辑
printf("This is the only running instance of the application.\n");

// 程序结束前解锁
if (flock(lock_fd, LOCK_UN) == -1) {
perror("flock");
close(lock_fd);
exit(EXIT_FAILURE);
}

close(lock_fd);
return 0;
}

posted @ 2024-04-25 15:05  王程根的技术博客  阅读(8)  评论(0编辑  收藏  举报