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

王朝system·作者佚名  2008-06-01
窄屏简体版  字體: |||超大  

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

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航