Linux进程监控背景与方法概述
无论后台服务程序的健壮性如何,仍有可能发生core dump等导致程序异常退出的情况。通常情况下,需要在无人工干预的环境下,使服务能够自动重新启动,从而确保持续为用户提供服务。
为此,需要部署一个监控程序来实现服务进程的自动重启功能。经过查阅相关资料及多种方法的尝试,本文总结了在Linux系统中监控重要进程并实现自动重启的两种主要方法:脚本检测法和子进程替换法。
基于Shell脚本的进程检测实现
1、脚本检测法
(1) 基本思路:利用Shell命令(如 ps -e | grep "$1" | grep -v "grep" | wc -l)来获取参数$1(即进程名称)对应的进程数量。脚本依据该数量决定后续操作。通过构建死循环,每隔几秒检查一次系统中指定程序的进程存活数,此逻辑也可通过crontab定时任务实现。
(2) 具体实现过程的代码如下:[ supervisor.sh ]
#! /bin/sh
# supervisor process
LOG_FILE=/var/log/supervisor_sh.log
# log function
function log() {
local t=$(date +"%F %X")
echo "[ $t ] $0 : $1 " >> ${LOG_FILE}
}
# check process number
# $1 : process name
function check_process() {
if [ -z $1 ]; then
log "Input parameter is empty."
return 0
fi
p_num=$(ps -e | grep "$1" | grep -v "grep" | wc -l)
log "p_num = $p_num"
echo $p_num
}
# supervisor process
while [ 1 ]
do
declare -i ch_num
p_name="apache2"
ch_num=$(check_process $p_name)
if [ $ch_num -eq 0 ]; then
killall $p_name
service $p_name start
fi
sleep 3
done
基于C语言子进程替换的监控机制
2、子进程替换法
(1) 基本思路:
a. 调用fork函数创建一个新进程,在进程表中生成新的表项。创建者(父进程)继续按原流程执行,而子进程则执行其自身的控制流程。
b. 运用execv函数将当前进程映像替换为新进程,新进程由path或file参数指定。借助execv函数,可以将程序的执行从一个可执行文件切换到另一个。
c. 当fork启动子进程后,子进程拥有独立的生命周期并运行。此时,可在父进程中调用wait函数,使父进程阻塞等待子进程结束。
(2) 基本的实现步骤:
a. 首先使用fork系统调用创建子进程。
b. 在子进程中调用execv函数,执行需要自动重启的目标程序。
c. 在父进程中执行wait函数等待子进程结束,随后重新创建一个新的子进程,形成闭环。
(3) 具体实现的代码如下:supervisor.c
/**
*
* supervisor
*
* date: 2026-08-10
*
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define LOG_FILE "/var/log/supervisor.log"
void s_log(char *text) {
time_t t;
struct tm *tm;
char *log_file;
FILE *fp_log;
char date[128];
log_file = LOG_FILE;
fp_log = fopen(log_file, "a+");
if (NULL == fp_log) {
fprintf(stderr, "Could not open logfile '%s' for writing\n", log_file);
}
time(&t);
tm = localtime(&t);
strftime(date, 127, "%Y-%m-%d %H:%M:%S", tm);
/* write the message to stdout and/or logfile */
fprintf(fp_log, "[%s] %s\n", date, text);
fflush(fp_log);
fclose(fp_log);
}
int main(int argc, char **argv) {
int ret, i, status;
char *child_argv[100] = {0};
pid_t pid;
if (argc < 2) {
fprintf(stderr, "Usage:%s ", argv[0]);
return -1;
}
for (i = 1; i < argc; ++i) {
child_argv[i-1] = (char *)malloc(strlen(argv[i])+1);
strncpy(child_argv[i-1], argv[i], strlen(argv[i]));
//child_argv[i-1][strlen(argv[i])] = '0';
}
while(1) {
pid = fork();
if (pid == -1) {
fprintf(stderr, "fork() error.errno:%d error:%s", errno, strerror(errno));
break;
}
if (pid == 0) {
s_log(child_argv[0]);
ret = execv(child_argv[0], (char **)child_argv);
s_log("execv return");
if (ret < 0) {
fprintf(stderr, "execv ret:%d errno:%d error:%s", ret, errno, strerror(errno));
continue;
}
s_log("exit child process");
exit(0);
}
if (pid > 0) {
pid = wait(&status);
fprintf(stdout, "Child process id: %d\n", pid);
//fprintf(stdout, "wait return");
s_log("Wait child process return");
}
}
return 0;
}
测试环境与进程行为验证分析
(4) 测试验证
a. 假设需要自动重启的目标程序为demo.c,其代码实现如下所示:
/*
*
* demo
*
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define LOG_FILE "/var/log/demo.log"
void demo_log(int num) {
time_t t;
struct tm *tm;
char *log_file;
FILE *fp_log;
char date[128];
log_file = LOG_FILE;
fp_log = fopen(log_file, "a+");
if (NULL == fp_log) {
fprintf(stderr, "Could not open logfile '%s' for writing\n", log_file);
}
time(&t);
tm = localtime(&t);
strftime(date,127,"%Y-%m-%d %H:%M:%S",tm);
/* write the message to stdout and/or logfile */
fprintf(fp_log, "[%s] num = %d\n", date, num);
fflush(fp_log);
fclose(fp_log);
}
int main(int argc, char **argv[]) {
int num = 0;
while(1) {
sleep(10);
num++;
demo_log(num);
}
}
b. 测试准备和说明:
b1. 上述相关服务程序编译后的二进制文件分别为:supervisor 和 demo。
b2. 执行以下测试命令:./supervisor ./demo
c. 测试的结果:
c1. execv(progname, arg) 执行成功后,其后的代码不会执行;仅当执行错误时,才会返回 -1。原调用execv进程的代码段会被progname应用程序的代码段完全替换。
c2. 当kill掉子进程时,父进程的wait函数会接收到子进程退出的信号,进而循环再次启动子进程,此过程具有极高的实时性。
c3. 当kill掉父进程时,子进程会被init进程接管。如果此时再kill掉子进程,则子进程会正常退出。
c4. 当同时kill掉父子进程时,父子进程都会退出。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。