Linux下防止某个程序两次运行的方法
通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利用open语句创建该文件,程序退出时关闭并删除此文件。(www.iocblog.net 文章来源)
| 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 ", file_lock); exit_file(10); } else { fprintf(stderr, "file: unable to create lock file "%s" (%d %s) " , file_lock, errno, strerror(errno)); exit_file(1);(www.iocblog.net 文章来源) } } file_lock_created = true; return fd; } static bool fill_lock(int lockfd) { char buf[30]; /* holds " " */ pid_t pid; int len; pid = getpid(); len = snprintf(buf, sizeof(buf), "%u ", (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? */ } } |
Tag: lock
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。