用文件锁实现程序只能有一个进程实例

用文件锁实现程序只能有一个进程实例

原理:利用文件锁,如果能加唯一写锁说明没有程序占用,否则已有进程,关闭该进程。
用途:用于需要单进程实例的程序比如守护进程。
代码示例:
//
// Created by windyear_office on 19-2-28.
// 一个用文件锁实现进程只能打开单个实例的程序。
#include <fcntl.h>    // fcntl sturct flock
#include <stdlib.h>  // exit
#include <stdio.h>  // printf
#include <unistd.h> // close
#include <errno.h> // errno
#include <string.h> // strlen
#define lockfile "OneInstance.pid"
int LockFile(int fd){
  // flock结构体表明锁的一些设置
  struct flock f1;
  f1.l_type = F_WRLCK; // 设置为唯一写锁,如果是同一个进程不会失败,会替换原来的锁。
  f1.l_start = 0;
  f1.l_whence = SEEK_SET;
  f1.l_len = 0; // 设置锁的大小为为整个文件
  return fcntl(fd, F_SETLK, &f1); //出错会返回,errno为EACCES或者EAGAIN。
}

int main(){
    int fd;
    fd = open(lockfile, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if(fd < 0){
	  printf("can't open the lock file.\n");
	  exit(1);
	}
    // 进行加锁操作
    if(LockFile(fd) < 0){
	  if(errno == EACCES || errno == EAGAIN){
		printf("The process only can have one instance.\n");
		close(fd);
		return 1;
	  }
	  printf("can't lock.\n");
	  exit(-1);
	}

    // 截断文件
  ftruncate(fd, 0);
  char buf[32];
  sprintf(buf, "%ld", (long)getpid());
  write(fd, buf, strlen(buf)+1);
  while(1){
	printf("It's the one instance process.\n");
	sleep(1);
  }
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值