Linux Shell自动拉起进程

1、前期准备

新建文件夹/root/test/,test文件夹中有myCPP.cpp,myTEXT.txt,restart.sh

2、myCPP.cpp

该文件的功能是每隔5s往myTEXT.txt中写入当前时间
编译得到可执行文件mycpp:g++ myCPP.cpp -std=c++11 -o mycpp
注意有时候因为权限问题会导致shell拉起失败,这里粗暴地开放所有权限chmod 777 mycpp

#include <string>
#include <stdio.h> 
#include <time.h>  
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <unistd.h>
using namespace std;
 
int main() {    
  while(1) {
    time_t rawtime;
    struct tm * timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    mktime(timeinfo);
    string tempDate = to_string(timeinfo->tm_year + 1900) + "-" +
                      to_string(timeinfo->tm_mon + 1)     + "-" +
                      to_string(timeinfo->tm_mday)        + "-" +
                      to_string(timeinfo->tm_hour)        + "-" +
                      to_string(timeinfo->tm_min)         + "-" +
                      to_string(timeinfo->tm_sec);
    ofstream ofs;
    ofs.open("/root/test/myTEXT.txt", ios::app);
    ofs << tempDate << endl;
    sleep(5);
  }
  return 0;
}

3、restart.sh

shell脚本,检测目标程序是否处于运行状态,如果不运行则将其拉起。

script_name="restart.sh" # 脚本的名字,用以在查找进程时过滤掉当前脚本的进程

# 检查文件是否存在
# @param $1:要监控的程序的目录
function check_file() {
    if [ $# -ne 1 ]; then
        echo "参数错误,正确使用方法: check_file /dir/file"
        return 1;
    fi

    if [ ! -f $1 ]; then
        echo "文件 $1 不存在"
        return 1
    fi
}

# return 0:进程没有运行 1:进程已运行
# @param $1:要监控的程序的目录
function monitor_process() {
    if [ $# -ne 1 ]; then
        echo "参数错误,正确使用方法:monitor_process /dir/file"
        return 1
    fi

    process_exists=$(ps -ef | grep $1 | grep -v grep | grep -v $script_name | wc -l)
    
    if [ $process_exists -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

# 启动监控程序
# @param $1:要监控的程序的目录
function start_monitor() {
    if [ $# -ne 1 ]; then
        echo "参数错误,正确使用方法:start_monitor /dir/file"
        return 1
    fi

    process_path=$1
    process_name=$(echo $process_path | awk -F / '{print $NF}')
    
    monitor_process $process_name
    if [ $? -eq 0 ]; then
        echo "该进程没有运行:$process_path"
        echo "现将启动进程"

        $process_path &
        monitor_process $process_name
        if [ $? -eq 1 ]; then
            echo "重启进程成功"
        else
            echo "重启进程失败"
        fi
     else
        echo "进程已经启动"
     fi   
}

# 主程序
# @param $1:要监控的程序的目录
if [ $# -ne 1 ]; then
    echo "参数错误,正确使用方法:ecdata_proc_monitor /dir/file"
    exit 1
fi

check_file $1
if [ $? -ne 0 ]; then
    exit 1
fi

start_monitor $1

4、加上crontab

加上crontab就可以让脚本定时执行,一旦发现进程没有运行,则启动该进程,这样就实现了进程的自动拉起。

// crontab基本命令
crontab -l #查看任务
crontab -e #编辑任务
crontab -r #删除用户所有的crontab的内容(慎用)

通过crontab -e进入类似vim的操作界面,在文件末尾补充*/1 * * * * /root/test/restart.sh /root/test/mycpp&,让restart.sh脚本每一分钟运行一次(即每分钟检测一次mycpp是否正在执行)

5、查看结果

查看mycpp进程是否在执行 ps -ef | grep mycpp
查看mycpp执行写入的结果 tail -f myTEXT.txt

查看写入时间结果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。