在Linux下防止某个程序被运行两次的方法

资讯 驱动中国 4,459 次阅读 0 条评论
分享 Q
 

通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利用open语句创建该文件,程序退出时关闭并删除此文件。

static char file_lock[sizeof(ctl_addr.sun_path)] = /var/run/file.pid;
static bool file_lock_created = FALSE;

static int
create_lock(void)
{
 int fd = open(file_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
 S_IRUSR | S_IRGRP | S_IROTH);

 if (fd < 0)
 {
 if (errno == EEXIST)
 {
 fprintf(stderr, "file: lock file \"%s\" already exists\n", file_lock);
 exit_file(10);
 }
 else
 {
 fprintf(stderr, "file: unable to create lock file \"%s\" (%d %s)\n"
 , file_lock, errno, strerror(errno));
 exit_file(1);
 }
 }
 file_lock_created = TRUE;
 return fd;
}

static bool
fill_lock(int lockfd)
{
 char buf[30]; /* holds "\n" */
 pid_t pid;
 int len;

 pid = getpid();
 len = snprintf(buf, sizeof(buf), "%u\n", (unsigned int) pid);
 bool ok = len > 0 && write(lockfd, buf, len) == len;

 close(lockfd);
 return ok;
}

static void
delete_lock(void)
{
 if (file_lock_created)
 {
 //delete_ctl_socket();
 unlink(file_lock); /* is noting failure useful? */
 }
}
版权声明:本文由驱动中国整理发布,转载需注明出处与原文链接。如有疑问请联系 editor@qudong.com
本文价值 成为第一个评分的人
登录后为本文打分
网友评论0 条评论
正在回复 的评论取消
评论加载中…
🔐

登录后参与互动

评论、点赞均可赚积分
连续签到、邀请好友也有奖励 🎁

电脑端: 微信扫码登录 微信内: 一键登录

微信扫一扫

打开微信「扫一扫」,分享本文到朋友圈或好友