读书人

看护进程+记录锁阻止程序重复运行

发布时间: 2013-03-25 15:43:04 作者: rapoo

守护进程+记录锁阻止程序重复运行

守护进程:

void Init_Daemon()
{
int pid;
pid = fork();
if(pid > 0) //parent
exit(0);
else if(pid < 0) //error
exit(1);

//子进程继续执行。父进程终止
setsid();

if(pid = fork())
exit(0);
else if(pid < 0)
exit(1);

//close handle of file。此处不知道为什么
for(int i=0; i<3; ++i)
close(i);

chdir("/");
umask(0);
return;
}

记录锁:

int test(int fd)
{
struct flock flk;
flk.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, or F_UNLCK */
flk.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
flk.l_start = 0; /* starting offset relative to l_whence */
flk.l_len = 0; /* len == 0 means "until end of file" */
flk.l_pid = getpid(); /* Process ID of the process holding the
lock, returned with F_GETLK */
return fcntl(fd, F_SETLK, &flk);
}

int fd;
if ((fd = open(strPIDFileName, O_RDWR | O_CREAT, FILE_MODE)) < 0)
{
exit(1);
}
if(test(fd) < 0) //返回值小于0.锁定不成功。
return 0;

读书人网 >编程

热点推荐