linux文件锁(保证只能同时启动一个实例,不同时启动多个实例)_linux 只运行一个实例_Dontla的博客-CSDN博客
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/file.h>
-
- int main() {
- // 打开一个特定的文件
- int fd = open("/tmp/my_program.lock", O_RDWR | O_CREAT, 0644);
- if (fd == -1) {
- perror("open");
- exit(1);
- }
-
- // 尝试对文件加锁
- int ret = flock(fd, LOCK_EX | LOCK_NB);
- if (ret == -1) {
- printf("Another instance is already running.\n");
- exit(0);
- }
-
- // 加锁成功,程序继续执行
- printf("Running...\n");
- sleep(10);
-
- // 解锁并关闭文件
- flock(fd, LOCK_UN);
- close(fd);
-
- return 0;
- }