|
|

楼主 |
发表于 2005-11-4 09:47:48
|
显示全部楼层
楼上的也是一种方法,我是看着apaue来做的贴出来,大家给找找问题.
//tigeroar.org
//2005-10-8
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <time.h>
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////////////////
//tigeroar
//2005-11-3
#define write_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLK,F_WRLCK,offset,whence,len)
#define un_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLK,F_UNLCK,offset,whence,len)
#define PIDFILE "daemon.pid"
int lock_reg(int fd,int cmd,int type,off_t offset,int whence,off_t len);
int main(int argc, char *argv[])
{
int lockfd;
char buf[16];
if((lockfd = open(PIDFILE,O_WRONLY|O_CREAT))<0)
{
printf("open error\n");
perror("open :\n");
}
if(write_lock(lockfd,0,SEEK_END,0)<0)
{
if(errno==EACCES||errno==EAGAIN)
exit(0);
else
printf("write_lock error\n");
}
if(ftruncate(lockfd,0)<0)
syslog(LOG_ERR,"ftruncate error\n");
sprintf(buf,"%d\n",getpid());
if(write(lockfd,buf,strlen(buf))!=strlen(buf))
syslog(LOG_ERR,"write pid error\n");
un_lock(lockfd,0,SEEK_SET,0);
close(lockfd);
return EXIT_SUCCESS;
}
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));
} |
|