在一些情况下,一个进程只能产生一个实例来执行。Unix环境,提供了文件-记录锁(file- and record-locking)机制,提供了事项单实例进程的基本解决方案。假如,一个进程在开始运行时,生成了一个文件,并且,对整个文件上锁,并且,只有一个这样的写锁允许生成。如果,后续的进程要试图产生写锁,会导致失败。这暗示了,前面已经有实例运行了。下面一个判断是否有实例运行的方法。每个实例,都会试图生成一个文件(/var/run/daemon.pid).如果文件已经锁上了,lockfile方法,返回失败,判断函数返回1,表示进程已经运行了。如果没有实例运行,程序,清空文件,写入进程id,返回0.下面为一个实现的程序:
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <syslog.h>
- #include <string.h>
- #include <errno.h>
- #include <sys/stat.h>
- #define LOCKFILE "/var/run/daemon.pid"
- #define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
- int already_running(void);
- int lockfile(int );
- int main(int argc,char * argv[])
- {
- int val = already_running();
- if(val == 0)
- {
- printf("sart to running...
");
- }
- else
- {
- printf("alredy running...
");
- exit(0);
- }
- while(1)
- {
- sleep(3);
- printf("...
");
- }
- return 0;
- }
- int already_running(void)
- {
- int fd;
- char buf[16];
- fd = open(LOCKFILE,O_RDWR|O_CREAT, LOCKMODE);
- if(fd < 0)
- {
- syslog(LOG_ERR, "can"t open %s: %s", LOCKFILE, strerror(errno));
- exit(1);
- }
- if(lockfile(fd) < 0)
- {
- if (errno == EACCES || errno == EAGAIN)
- {
- close(fd);
- return 1;
- }
- syslog(LOG_ERR,"can"t lock %s: %s", LOCKFILE, strerror(errno));
- exit(1);
- }
- ftruncate(fd,0);
- sprintf(buf,"%ld",(long)getpid());
- write(fd,buf,strlen(buf) + 1);
- return 0;
- }
- int lockfile(int fd)
- {
- struct flock fl;
- fl.l_type = F_WRLCK;
- fl.l_start = 0;
- fl.l_whence = SEEK_SET;
- fl.l_len = 0;
- return(fcntl(fd, F_SETLK, &fl));
- }
Unix环境文件读写锁Unix环境写入文件时要注意小细节相关资讯 UNIX
- 一个涵盖 Unix 44 年进化史的版本 (12/23/2015 19:08:29)
- 2002年,程序员和Unix大神们的桌面 (11/10/2015 08:18:44)
- 20个 Unix/Linux 命令技巧 (03/22/2015 08:09:34)
| - UNIX 家族小史 (12/01/2015 12:03:06)
- 从Unix 和 PC机:重释Linux的起源 (05/17/2015 21:13:04)
- 什么是Unix以及它为什么这么重要? (07/23/2014 16:47:39)
|
本文评论 查看全部评论 (0)