防止进程重新启动-keepalived源码解析

来源:互联网 发布:中草药软件 编辑:程序博客网 时间:2024/06/06 02:47

  在上面一篇文章中,写了一种防止进程重新启动的方式:文件盒记录锁(fcntl()和F_SETLK(设置记录所))

  在解析keepalived源码时,见到一种防止进程重启的方式,现在整理处理进行分享。

  在keepalived的处理中,使用的主要函数:int kill(pid_t pid, int sig)和int unlink(const char* filename)。

  下面来看下这两个函数的主要功能:

   kill函数

    头文件:signal.h   sys/types.h

    函数形式:int kill(pid_t pid, int sig);

    函数功能:向任何进程组或进程发送信号

    参数说明:

      pid  进程号

        pid>0     pid是信号欲送往的进程的标识

        pid=0     信号将送往所有与调用kill()的那个进程属同一个使用组的进程

        pid=-1    信号将送往所有条用进程有权给其发送信号的进程

        pid<-1    信号将送往以-pid为组标识的进程

      sig  信号代码

        如果为0,则没有任何信号送出,但是系统会执行错误检查。通常会利用sig值为零来检验某个进程是否仍在执行(防止进程重新启动就是使用该功能)。


  unlink函数

    头文件:unistd.h

    函数形式:int unlink(const *filename)

   功能:减少一个连接数,如果连接数为0并且没有任何进程打开该文件,该文件就会被删除。如果有进程打开该文件,那么该文件暂时不删除,直到所有打开该文件的进程都结束时文件才能被删除。


  keepalived的处理如下所示:

  检查是否已经启动:

intprocess_running(char *pid_file){  /* 打开pidfile */  FILE *pidfile = fopen(pid_file, "r");  pid_t pid;  int ret;  /* No pidfile ,表示该进程没有启动 */  if (!pidfile)    return 0;  /* 读取pidfile中的参数赋值给pid(该参数为进程号) */  ret = fscanf(pidfile, "%d", &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 */  if (kill(pid, 0)) {    log_message(LOG_INFO, "Remove a zombie pid file %s", pid_file);<strong>    /*删除和该文件的连接*/    unlink(pidfile);</strong>    return 0;  }  return 1;}<strong></strong>


  创建守护进程pidfile文件

intpidfile_write(char *pid_file, int pid){  FILE *pidfile = NULL;  /* 创建文件 */  /* 参数mode设定,只有在建立新文件时才会有效   * S_IRUSR: 代表该文件所有者具有可读的权限   * S_IWUSR: 代表该文件所有者具有可写的权限   * S_IRGRP: 代表该文件用户组具有可读的权限   * S_IROTH: 代表该其他用户具有可读的权限   */  int pidfd = creat(pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);  /* 在一个已经打开的文件描述符上打开一个流 */  if (pidfd != -1)     pidfile = fdopen(pidfd, "w");  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;}


0 0
原创粉丝点击