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

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

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

#include

#include

#include

#include

#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;

}

编译:

gcc -o test test.c设计

运行:code

1. 打开终端: ./test进程

cat /var/run/test.pid23409ip

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

Fail to fcntl F_SETLK: Resource temporarily unavailablestring

表示程序已经有实例运行it

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值