Linux下程序单例模式的保证机制:/var/run/*.pid

在Linux 系统中/var/run下有很多以pid结尾的文件,这个其实是为了保证程序以单例模式运行而设计的。程序在启动后,首先打开(如果没有则创建)/var/run/xx.pid,然后尝试去设置文件锁,如果成功,则将程序的进程ID写入该文件,写入后注意不要关闭文件或解锁;如果加锁失败,表明程序已经有一个进程在运行了,则退出此次启动。此机制在一些程序尤其是服务器程序中很常见,例如sip 服务器kamailio中就是这样保证程序以单例模式运行的。

注:程序退出后,文件锁自动解锁。


<span style="font-size:18px;">#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>

#define DEFAULT_FILE "/var/run/test.pid"

int main(int argc, char *argv[])
{
int fd = -1;
char buf[32];

fd = open(DEFAULT_FILE, O_WRONLY | O_CREAT, 0666);
if (fd < 0) {
perror("Fail to open");
exit(1);
}

struct flock lock;
bzero(&lock, sizeof(lock));

if (fcntl(fd, F_GETLK, &lock) < 0) {
perror("Fail to fcntl F_GETLK");
exit(1);
}

lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;

if (fcntl(fd, F_SETLK, &lock) < 0) {
perror("Fail to fcntl F_SETLK");
exit(1);
}

pid_t pid = getpid();
int len = snprintf(buf, 32, "%d\n", (int)pid);

write(fd, buf, len); //Write pid to the file

printf("Hello world\n");

while(1);
return 0;
}
</span>

编译:

gcc -o test test.c

运行: 

1. 打开终端: ./test

cat /var/run/test.pid 
23409

2. 打开另一终端:./test,打印错误如下

Fail to fcntl F_SETLK: Resource temporarily unavailable

表示程序已经有实例运行

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪游东戴河

你就是这个世界的唯一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值