防止进程重新启动-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>
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;}
- 防止进程重新启动-keepalived源码解析
- 守护进程的创建-keepalived源码解析
- keepalived源码浅析——Daemon进程
- syslog函数处理-keepalived源码解析
- Linux源码解析-进程-进程
- Linux下防止程序重新启动
- keepalived源码浅析——Global_data全局数据解析
- keepalived源码浅析——parser关键字解析
- Android 进程启动源码解析
- Linux源码解析-进程-进程状态
- 遍历并监视,重新启动进程
- Linux-----源码安装keepalived
- keepalived 个人解析
- Redis解析之Keepalived
- Fresco 源码解析 - 利用 @DoNotSkip 来防止混淆
- 源码深度解析spring中防止乱码的过滤器
- Android源码解析之应用程序启动进程
- 结束进程和重新启动的vbs脚本
- hdu 4111 Alice and Bob(博弈)
- poj 1422 最小路径覆盖
- HDU Clear All of Them I(状态压缩+DP+记忆搜索)
- 个人对多线程的总结
- Android单元测试jUnit
- 防止进程重新启动-keepalived源码解析
- java内存管理
- Hduoj3874 【离线+树状数组】
- 2014-11-8Android学习------Android抽屉效果的实现案例--------动画Animation学习篇
- 构建高性能Web站点(修订版)笔记
- JSP九大内置对象
- HDU 4786 Fibonacci Tree 并查集+生成树=kruskal
- H264 GOP 扫盲
- POJ 2074 Line of Sight 直线相交+线段覆盖