Linux监控重要进程的实现方法

不管后台服务程序写的多么健壮,还是可能会出现core dump等程序异常退出的情况,但是一般情况下需要在无

人为干预情况下,能够自动重新启动,保证服务进程能够服务用户。这时就需要一个监控程序来实现能够让服务进程自动重新启动。查阅相关资料及尝试一些方法之后,总结linux系统监控重要进程的实现方法:脚本检测和子进程替换。

1、脚本检测 (1) 基本思路: 通过shell命令(ps -e | grep "$1" | grep -v "grep" | wc -l) 获取 $1 ($1 代表进程的名字)的进程数,脚本根据进程数来决定下一步的操作。通过一个死循环,每隔几秒检查一次系统中的指定程序的进程数,这里也可使用crontab来实现。 (2) 具体实现过程的代码如下: [ supervisor.sh ]

  1. #! /bin/sh
  2. # supervisor process
  3. LOG_FILE=/var/log/supervisor_sh.log
  4. # log function
  5. function log() {
  6. local t=$(date +"%F %X")
  7. echo "[ $t ] $0 : $1 " >> ${LOG_FILE}
  8. }
  9. # check process number
  10. # $1 : process name
  11. function check_process() {
  12. if [ -z $1 ]; then
  13. log "Input parameter is empty."
  14. return 0
  15. fi
  16. p_num=$(ps -e | grep "$1" | grep -v "grep" | wc -l)
  17. log "p_num = $p_num"
  18. echo $p_num
  19. }
  20. # supervisor process
  21. while [ 1 ]
  22. do
  23. declare -i ch_num
  24. p_name="apache2"
  25. ch_num=$(check_process $p_name)
  26. if [ $ch_num -eq 0 ]; then
  27. killall $p_name
  28. service $p_name start
  29. fi
  30. sleep 3
  31. done
  1. #! /bin/sh
  2. # supervisor process
  3.  
  4. LOG_FILE=/var/log/supervisor_sh.log
  5.  
  6. # log function
  7. function log() {
  8. local t=$(date +"%F %X")
  9. echo "[ $t ] $0 : $1 " >> ${LOG_FILE}
  10. }
  11.  
  12. # check process number
  13. # $1 : process name
  14. function check_process() {
  15. if [ -z $1 ]; then
  16. log "Input parameter is empty."
  17. return 0
  18. fi
  19.  
  20. p_num=$(ps -e | grep "$1" | grep -v "grep" | wc -l)
  21. log "p_num = $p_num"
  22. echo $p_num
  23. }
  24.  
  25. # supervisor process
  26. while [ 1 ]
  27. do
  28. declare -i ch_num
  29. p_name="apache2"
  30. ch_num=$(check_process $p_name)
  31. if [ $ch_num -eq 0 ]; then
  32. killall $p_name
  33. service $p_name start
  34. fi
  35. sleep 3
  36. done

2、子进程替换 (1) 基本思路:  a. 使用fork函数创建一个新的进程,在进程表中创建一个新的表项,而创建者(即父进程)按原来的流程继续执行,子进程执行自己的控制流程 b. 运用execv函数把当前进程替换为一个新的进程,新进程由path或file参数指定,可以使用execv函数将程序的执行从一个程序切换到另一个程序 c. 当fork启动一个子进程时,子进程就有了它自己的生命周期并将独立运行,此时可以在父进程中调用wait函数让父进程等待子进程的结束 (2) 基本的实现步骤:  a. 首先使用fork系统调用,创建子进程 b. 在子进程中使用execv函数,执行需要自动重启的程序 c. 在父进程中执行wait函数等待子进程的结束,然后重新创建一个新的子进程 (3) 具体实现的代码如下: supervisor.c

  1. /**
  2. *
  3. * supervisor
  4. *
  5. * date: 2016-08-10
  6. *
  7. */
  8. #include <stdio.h>
  9. #include <unistd.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. #include <sys/types.h>
  13. #include <sys/wait.h>
  14. #include <stdlib.h>
  15. #include <time.h>
  16. #define LOG_FILE "/var/log/supervisor.log"
  17. void s_log(char *text) {
  18. time_t      t;
  19. struct tm  *tm;
  20. char *log_file;
  21. FILE *fp_log;
  22. char date[128];
  23. log_file = LOG_FILE;
  24. fp_log = fopen(log_file, "a+");
  25. if (NULL == fp_log) {
  26. fprintf(stderr, "Could not open logfile '%s' for writing\n", log_file);
  27. }
  28. time(&t);
  29. tm = localtime(&t);
  30. strftime(date, 127, "%Y-%m-%d %H:%M:%S", tm);
  31. /* write the message to stdout and/or logfile */
  32. fprintf(fp_log, "[%s] %s\n", date, text);
  33. fflush(fp_log);
  34. fclose(fp_log);
  35. }
  36. int main(int argc, char **argv) {
  37. int ret, i, status;
  38. char *child_argv[100] = {0};
  39. pid_t pid;
  40. if (argc < 2) {
  41. fprintf(stderr, "Usage:%s <exe_path> <args...>", argv[0]);
  42. return -1;
  43. }
  44. for (i = 1; i < argc; ++i) {
  45. child_argv[i-1] = (char *)malloc(strlen(argv[i])+1);
  46. strncpy(child_argv[i-1], argv[i], strlen(argv[i]));
  47. //child_argv[i-1][strlen(argv[i])] = '0';
  48. }
  49. while(1) {
  50. pid = fork();
  51. if (pid == -1) {
  52. fprintf(stderr, "fork() error.errno:%d error:%s", errno, strerror(errno));
  53. break;
  54. }
  55. if (pid == 0) {
  56. s_log(child_argv[0]);
  57. ret = execv(child_argv[0], (char **)child_argv);
  58. s_log("execv return");
  59. if (ret < 0) {
  60. fprintf(stderr, "execv ret:%d errno:%d error:%s", ret, errno, strerror(errno));
  61. continue;
  62. }
  63. s_log("exit child process");
  64. exit(0);
  65. }
  66. if (pid > 0) {
  67. pid = wait(&status);
  68. fprintf(stdout, "Child process id: %d\n", pid);
  69. //fprintf(stdout, "wait return");
  70. s_log("Wait child process return");
  71. }
  72. }
  73. return 0;
  74. }
  1. /**
  2. *
  3. * supervisor
  4. *
  5. * date: 2016-08-10
  6. *
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <unistd.h>
  11. #include <errno.h>
  12. #include <string.h>
  13. #include <sys/types.h>
  14. #include <sys/wait.h>
  15. #include <stdlib.h>
  16. #include <time.h>
  17.  
  18. #define LOG_FILE "/var/log/supervisor.log"
  19.  
  20. void s_log(char *text) {
  21. time_t t;
  22. struct tm *tm;
  23. char *log_file;
  24. FILE *fp_log;
  25. char date[128];
  26.  
  27. log_file = LOG_FILE;
  28. fp_log = fopen(log_file, "a+");
  29. if (NULL == fp_log) {
  30. fprintf(stderr, "Could not open logfile '%s' for writing\n", log_file);
  31. }
  32.  
  33. time(&t);
  34. tm = localtime(&t);
  35. strftime(date, 127, "%Y-%m-%d %H:%M:%S", tm);
  36.  
  37. /* write the message to stdout and/or logfile */
  38. fprintf(fp_log, "[%s] %s\n", date, text);
  39. fflush(fp_log);
  40. fclose(fp_log);
  41. }
  42.  
  43. int main(int argc, char **argv) {
  44. int ret, i, status;
  45. char *child_argv[100] = {0};
  46. pid_t pid;
  47. if (argc < 2) {
  48. fprintf(stderr, "Usage:%s <exe_path> <args...>", argv[0]);
  49. return -1;
  50. }
  51.  
  52. for (i = 1; i < argc; ++i) {
  53. child_argv[i-1] = (char *)malloc(strlen(argv[i])+1);
  54. strncpy(child_argv[i-1], argv[i], strlen(argv[i]));
  55. //child_argv[i-1][strlen(argv[i])] = '0';
  56. }
  57.  
  58. while(1) {
  59. pid = fork();
  60. if (pid == -1) {
  61. fprintf(stderr, "fork() error.errno:%d error:%s", errno, strerror(errno));
  62. break;
  63. }
  64. if (pid == 0) {
  65. s_log(child_argv[0]);
  66. ret = execv(child_argv[0], (char **)child_argv);
  67. s_log("execv return");
  68. if (ret < 0) {
  69. fprintf(stderr, "execv ret:%d errno:%d error:%s", ret, errno, strerror(errno));
  70. continue;
  71. }
  72. s_log("exit child process");
  73. exit(0);
  74. }
  75. if (pid > 0) {
  76. pid = wait(&status);
  77. fprintf(stdout, "Child process id: %d\n", pid);
  78. //fprintf(stdout, "wait return");
  79. s_log("Wait child process return");
  80. }
  81. }
  82.  
  83. return 0;
  84. }

(4) 测试验证 a. 假设需要自动重启的程序为demo.c,其代码实现如下所示:

  1. /*
  2. *
  3. * demo
  4. *
  5. */
  6. #include <stdio.h>
  7. #include <unistd.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12. #include <stdlib.h>
  13. #include <time.h>
  14. #define LOG_FILE "/var/log/demo.log"
  15. void demo_log(int num) {
  16. time_t      t;
  17. struct tm  *tm;
  18. char *log_file;
  19. FILE *fp_log;
  20. char date[128];
  21. log_file = LOG_FILE;
  22. fp_log = fopen(log_file, "a+");
  23. if (NULL == fp_log) {
  24. fprintf(stderr, "Could not open logfile '%s' for writing\n", log_file);
  25. }
  26. time(&t);
  27. tm = localtime(&t);
  28. strftime(date,127,"%Y-%m-%d %H:%M:%S",tm);
  29. /* write the message to stdout and/or logfile */
  30. fprintf(fp_log, "[%s] num = %d\n", date, num);
  31. fflush(fp_log);
  32. fclose(fp_log);
  33. }
  34. int main(int argc, char **argv[]) {
  35. int num = 0;
  36. while(1) {
  37. sleep(10);
  38. num++;
  39. demo_log(num);
  40. }
  41. }
  1. /*
  2. *
  3. * demo
  4. *
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <unistd.h>
  9. #include <errno.h>
  10. #include <string.h>
  11. #include <sys/types.h>
  12. #include <sys/wait.h>
  13. #include <stdlib.h>
  14. #include <time.h>
  15.  
  16. #define LOG_FILE "/var/log/demo.log"
  17.  
  18. void demo_log(int num) {
  19. time_t t;
  20. struct tm *tm;
  21. char *log_file;
  22. FILE *fp_log;
  23. char date[128];
  24.  
  25. log_file = LOG_FILE;
  26. fp_log = fopen(log_file, "a+");
  27. if (NULL == fp_log) {
  28. fprintf(stderr, "Could not open logfile '%s' for writing\n", log_file);
  29. }
  30.  
  31. time(&t);
  32. tm = localtime(&t);
  33. strftime(date,127,"%Y-%m-%d %H:%M:%S",tm);
  34.  
  35. /* write the message to stdout and/or logfile */
  36. fprintf(fp_log, "[%s] num = %d\n", date, num);
  37. fflush(fp_log);
  38. fclose(fp_log);
  39. }
  40.  
  41. int main(int argc, char **argv[]) {
  42. int num = 0;
  43.  
  44. while(1) {
  45. sleep(10);
  46. num++;
  47. demo_log(num);
  48. }
  49. }

b. 测试准备和说明:

b1. 以上相关服务程序编译后的二进制文件为: supervisor 和 demo

b2. 执行如下测试命令 ./supervisor ./demo

c. 测试的结果:

c1. execv(progname, arg) 执行成功后,其后的代码不会执行;只有当执行错误时,才会返回 -1。原来调用execv进程的代码段会被progname应用程序的代码段替换。

c2. 当kill掉子进程时,父进程wait函数会接收到子进程退出的信号,进而循环再启动子进程,此过程实时性非常高。

c3. 当kill掉父进程时,子进程会被init进程接管,如果此时再kill掉子进程,则子进程会退出。

c4. 当同时kill掉父子进程,则父子进程都会退出。

Linux监控重要进程的实现方法的更多相关文章

  1. Linux/Unix分配进程ID的方法以及源代码实现

    在Linux/Unix系统中.每一个进程都有一个非负整型表示的唯一进程ID.尽管是唯一的.可是进程的ID能够重用.当一个进程终止后,其进程ID就能够再次使用了. 大多数Linux/Unix系统採用延迟 ...

  2. 【Linux】- 守护进程的启动方法

    转自:Linux 守护进程的启动方法 Linux中"守护进程"(daemon)就是一直在后台运行的进程(daemon). 本文介绍如何将一个 Web 应用,启动为守护进程. 一.问 ...

  3. Linux的僵尸进程及其解决方法

    1. 产生原因: 在UNIX 系统中,一个进程结束了,但是他的父进程没有等待(调用wait / waitpid)他,那么他将变成一个僵尸进程.通过ps命令查看其带有defunct的标志.僵尸进程是一个 ...

  4. 利用VisualVm和JMX远程监控Java进程

    自Java 6开始,Java程序启动时都会在JVM内部启动一个JMX agent,JMX agent会启动一个MBean server组件,把MBeans(Java平台标准的MBean + 你自己创建 ...

  5. linux 创建守护进程的相关知识

    linux 创建守护进程的相关知识 http://www.114390.com/article/46410.htm linux 创建守护进程的相关知识,这篇文章主要介绍了linux 创建守护进程的相关 ...

  6. [转]❲阮一峰❳Linux 守护进程的启动方法

    ❲阮一峰❳Linux 守护进程的启动方法 "守护进程"(daemon)就是一直在后台运行的进程(daemon). 本文介绍如何将一个 Web 应用,启动为守护进程. 一.问题的由来 ...

  7. Linux中监控命令top命令使用方法详解

    收集了两篇关于介绍Linux中监控命令top命令的详细使用方法的文章.总的来说,top命令主要用来查看Linux系统的各个进程和系统资源占用情况,在监控Linux系统性能方面top显得非常有用,下面就 ...

  8. 使用 shell 脚本对 Linux 系统和进程资源进行监控

    Shell 简介 Shell 语言对于接触 LINUX 的人来说都比较熟悉,它是系统的用户界面,提供了用户与内核进行交互操作的一种接口.它接收用户输入的命令并把它送入内核去执行.实际上 Shell 是 ...

  9. Linux下,如何监控某个进程到底向哪个地址发起了网络调用

    Linux下,如何监控某个进程到底向哪个地址发起了网络调用 有时候,有些应用,比如idea,你发起某个操作时,其底层会去请求网络,获取一些数据. 但是不知道,请求了什么地址.举个例子,在idea中,m ...

随机推荐

  1. Python爬虫:抓取新浪新闻数据

    案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...

  2. es6 对象的扩展

    一.现在还有很多浏览器不能直接使用es6语法.特别是手机端的一些低版本的浏览器.都需要用bale转换一下. 但是目前流行的框架中(vue,react,angular).都有自己的脚手架,都能用webp ...

  3. button 和 submit 的区别

    表单提交中button和submit的区别submit是button的一个特例,也是button的一种,它把提交这个动作自动集成了,submit和button,二者都以按钮的形式展现,看起来都是按钮, ...

  4. Java结束线程的三种方法(爱奇艺面试)

    线程属于一次性消耗品,在执行完run()方法之后线程便会正常结束了,线程结束后便会销毁,不能再次start,只能重新建立新的线程对象,但有时run()方法是永远不会结束的.例如在程序中使用线程进行So ...

  5. canvas技术整理

    canvas技术整理 html <canvas id= "canvas"></canvas> javascript var canvas = documen ...

  6. 【设计模式】—— 访问者模式Visitor

    前言:[模式总览]——————————by xingoo 模式意图 对于某个对象或者一组对象,不同的访问者,产生的结果不同,执行操作也不同.此时,就是访问者模式的典型应用了. 应用场景 1 不同的子类 ...

  7. CF933A A Twisty Movement

    题意翻译 给定一个序列 A,你可以翻转其中的一个区间内的数,求翻转后的序列的最长不下降子序列的长度.(∣A∣≤2000,1≤ai≤2|A|\le 2000,1\le a_i \le 2∣A∣≤2000 ...

  8. 一步步创建第一个Docker App —— 4. 部署应用

    原文:https://docs.docker.com/engine/getstarted-voting-app/deploy-app/ 在这一步中,将会使用第一步提到的 docker-stack.ym ...

  9. 洛谷 P5108 仰望半月的夜空 解题报告

    P5108 仰望半月的夜空 题目描述 半月的夜空中,寄托了多少人与人之间的思念啊 曦月知道,这些思念会汇集成一个字符串\(S(n = |S|)\) 由于思念汇集的过于复杂,因此曦月希望提炼出所有的思念 ...

  10. bzoj 4328 始祖鸟

    4328: JSOI2012 始祖鸟 Time Limit: 10 Sec  Memory Limit: 256 MBSec  Special JudgeSubmit: 76  Solved: 52[ ...