Unix环境,产生单实例进程方案
来源:互联网 发布:java final static变量 编辑:程序博客网 时间:2024/06/03 22:26
在一些情况下,一个进程只能产生一个实例来执行。Unix环境,提供了文件-记录锁(file- and record-locking)机制,提供了事项单实例进程的基本解决方案。
假如,一个进程在开始运行时,生成了一个文件,并且,对整个文件上锁,并且,只有一个这样的写锁允许生成。
如果,后续的进程要试图产生写锁,会导致失败。这暗示了,前面已经有实例运行了。
下面一个判断是否有实例运行的方法。每个实例,都会试图生成一个文件(/var/run/daemon.pid).如果文件已经锁上了,lockfile方法失败,函数返回1,表示进程已经运行了。如果没有实例运行,lockfile方法成功,接着:清空文件,写入进程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.../n");
- }
- else
- {
- printf("alredy running.../n");
- exit(0);
- }
- while(1)
- {
- sleep(3);
- printf(".../n");
- }
- 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/Linux环境下,写入文件时。如果,在open函数的读写模式,只提供了,读写,如果不存在”生成“这些模式时。
如果源文件存在,以非追加的方式写入数据时,当后续的数据长度大于源文件已有的数据时,后续的文件覆盖以前的数据。
如果后续的数据长度小于源文件以后的数据长度时,只是覆盖了后续写入的数据长度。这时,文件的数据是两者的混合,这不是我们想要的。
所以为了数据的正确性,在以非追加(append)方式写入数据时,首先要清空,要写入的文件。
以下为一个例子:
- #include<stdio.h>
- #include<stdlib.h>
- #include<fcntl.h>
- int main(int argc ,char * argv[])
- {
- int val = 0;
- int fd = 0;
- char* fpath = "./test.txt";
- char buffer[] = "Hi i am harry.";
- char buffer1 []= "liyachao.";
- /*open the file with write/read and create module*/
- fd = open(fpath,O_RDWR|O_CREAT);
- /*truncate the exiting file's size to zero,meanning empty the exit file.*/
- ftruncate(fd,0);
- val = write(fd,buffer,strlen(buffer));
- printf("wirte %d bytes.",val);
- return 0;
- }
- Unix环境,产生单实例进程方案
- Unix环境产生单实例进程方案
- Unix环境,产生单实例进程方案
- Unix环境,产生单实例进程方案
- 《Unix环境高级编程》:单实例守护进程的实现
- 《Unix环境高级编程》:单实例守护进程的实现
- UNIX环境高级编程学习之第十三章守护进程 - 单实例的守护进程
- UNIX环境高级编程——单实例的守护进程
- UNIX/Linux-进程环境(实例入门篇)
- Unix环境编程------Unix编程实例------进程组&&会话
- UNIX进程环境小结
- Unix进程环境
- UNIX进程环境
- UNIX进程的环境
- Unix环境编程-进程环境
- C# 单进程实例
- Linux单实例进程
- Unix环境进程间通信
- 查询手机所在地理位置的简单方法
- 中断和轮询的方式
- 华为路由交换机常用命令
- poi Excel写操作帮助类
- 手机基站数据转经纬度
- Unix环境,产生单实例进程方案
- 基站id转GPS经纬度
- js触发.net服务器端事件
- 异常处理
- [Asp.Net]百万级分页
- 安特网定位api接口汇总
- Freescale 加速度计
- 算法学习【2】 - 1020. Big Integer
- byte[]转16进制bug总结