|
Pidfile.h 源码如下:
#ifndef _PIDFILE_H
#define _PIDFILE_H
/* system include */
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <syslog.h>
/* lock pidfile */
#define KEEPALIVED_PID_FILE "/var/run/keepalived.pid"
#define KEEPALIVED_VRRP_PID_FILE "/var/run/keepalived_vrrp.pid"
#define KEEPALIVED_CHECKERS_PID_FILE "/var/run/keepalived_checkers.pid"
#define VRRP_PID_FILE "/var/run/vrrp.pid"
#define CHECKERS_PID_FILE "/var/run/checkers.pid"
/* Prototypes */
extern int pidfile_write(char *, int);
extern void pidfile_rm(char *);
extern int keepalived_running(int);
#endif
Pidfile.c 源码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "logger.h"
#include "pidfile.h"
extern char *main_pidfile;
extern char *checkers_pidfile;
extern char *vrrp_pidfile;
/* Create the runnnig daemon pidfile */ #创建pid文件,将getpid()函数获取的pid写入文件
int
pidfile_write(char *pid_file, int pid)
{
FILE *pidfile = NULL;
int pidfd = creat(pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (pidfd != -1) pidfile = fdopen(pidfd, "w"); //fdopen()会将参数fildes 的文件描述词,转换为对应的文件指针后返回 if (!pidfile) {
log_message(LOG_INFO, "pidfile_write : Can not open %s pidfile",
pid_file);
return 0;
}
fprintf(pidfile, "%d\n", pid);
fclose(pidfile);
return 1;
}
/* Remove the running daemon pidfile */ //#删除pid文件
void
pidfile_rm(char *pid_file)
{
unlink(pid_file);
}
/* return the daemon running state */ //返回守护进程的运行状态 运行返回1 停止返回0
int
process_running(char *pid_file)
{
FILE *pidfile = fopen(pid_file, "r");
pid_t pid;
int ret;
/* No pidfile */ //pid文件不存在情况
if (!pidfile)
return 0;
ret = fscanf(pidfile, "%d", &pid); //获取pid文件中的pid数值
if (ret == EOF && ferror(pidfile) != 0) {
log_message(LOG_INFO, "Error opening pid file %s", pid_file);
}
fclose(pidfile);
/* If no process is attached to pidfile, remove it */ //如果对应的进程不存在则除去僵尸pid文件
if (kill(pid, 0)) {
log_message(LOG_INFO, "Remove a zombie pid file %s", pid_file);
pidfile_rm(pid_file);
return 0;
}
return 1;
}
/* Return parent process daemon state */ //判断父进程的运行状态 根据模式 分别判断主进程 vrrp checks等pid文件 运行返回1 停止返回0
int
keepalived_running(int mode)
{
if (process_running(main_pidfile))
return 1;
else if (mode & 1 || mode & 2)
return process_running((mode & 1) ? vrrp_pidfile :
checkers_pidfile);
if (process_running(vrrp_pidfile) ||
process_running(checkers_pidfile))
return 1;
return 0;
}
调用位置:
main.c中
/* write the father's pidfile */
if (!pidfile_write(main_pidfile, getpid()))
check_daemon.c中
/* Child process part, write pidfile */
if (!pidfile_write(checkers_pidfile, getpid())) {
log_message(LOG_INFO, "Healthcheck child process: cannot write pidfile");
exit(0);
}
vrrp_daemon.c 中
/* Child process part, write pidfile */
if (!pidfile_write(vrrp_pidfile, getpid())) {
/* Fatal error */
log_message(LOG_INFO, "VRRP child process: cannot write pidfile");
exit(0);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。 |
|
|