零零社区|百姓的网上家园-互动交流平台!(0.0)=^_^=(00社区)

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz

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

2013-4-5 16:58| 发布者: 123456000000| 查看: 12| 评论: 0

摘要: 通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利用open语句创建该文件,程序退出时关闭并删除此文件。 static char file_lock = /var/run/file.pid;  ...
 

通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利用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? */   }  }

路过

雷人

握手

鲜花

鸡蛋

相关阅读

发表评论

最新评论

相关分类


Archiver|手机版|小黑屋|00社区

GMT+8, 2023-1-31 10:50 , Processed in 0.041352 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

返回顶部