在linux下防止某个程序被运行两次的方法
来源:互联网 发布:淘宝店铺新店扶持政策 编辑:程序博客网 时间:2024/06/02 06:39
通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利用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? */
}
}
- 在linux下防止某个程序被运行两次的方法
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- (转)防止程序启动两次的方法
- 防止程序启动两次的方法CreateMutex()
- QT防止程序启动两次的方法
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法 CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- 防止程序启动两次的方法CreateMutex()
- [资源数据]合同类型代码
- 华为笔试
- 超链接的正则表达式匹配
- 一道面试题
- Build Your Own Video Community With Lighttpd And FlowPlayer (Debian Etch)
- 在linux下防止某个程序被运行两次的方法
- 中国php新动力,Jwork框架即将发表
- IE 打印之activex
- jpetstore4.0学习笔记
- ORACLE存储过程实战之二:游标
- jpetstore4.0学习笔记
- 测试
- SQL如何将表中的数据从纵向显示转换成横向显示
- jpetstore4.0学习笔记