fprintf(fp, "%s %s", datetime, pLoginfo);
fclose(fp);
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));
}
/* 只允许一个副本运行 */
void already_running(void)
{
int fd = -1;
char buf[16] = {0};
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, "%d", getpid());
write(fd, buf, strlen(buf));
close(fd);
}
/* 作为守护进程运行 */
void init_daemon(void)
{
int pid = -1;
if ((pid = fork())) {
exit(0);
} else if (pid < 0) {
exit(1);
}