单例守护进程实现
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <syslog.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <sys/stat.h>
#define LOCKFILE "daemon.pid"
#define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
int
lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
return(fcntl(fd, cmd, &lock));
}
int lockfile(int fd){
return lock_reg(fd,F_SETLK,F_WRLCK,0,SEEK_SET,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);
exit(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 main(int argc, char *argv[])
{
if(already_running()==0)
printf("can running");
else
printf("already running");
sleep(1000);
return 0;
}