1、前期準(zhǔn)備
新建文件夾/root/test/,test文件夾中有myCPP.cpp,myTEXT.txt,restart.sh
2、myCPP.cpp
該文件的功能是每隔5s往myTEXT.txt中寫入當(dāng)前時間
編譯得到可執(zhí)行文件mycpp:g++ myCPP.cpp -std=c++11 -o mycpp
注意有時候因?yàn)闄?quán)限問題會導(dǎo)致shell拉起失敗,這里粗暴地開放所有權(quán)限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腳本,檢測目標(biāo)程序是否處于運(yùn)行狀態(tài),如果不運(yùn)行則將其拉起。
script_name="restart.sh" # 腳本的名字,用以在查找進(jìn)程時過濾掉當(dāng)前腳本的進(jìn)程
# 檢查文件是否存在
# @param $1:要監(jiān)控的程序的目錄
function check_file() {
if [ $# -ne 1 ]; then
echo "參數(shù)錯誤,正確使用方法: check_file /dir/file"
return 1;
fi
if [ ! -f $1 ]; then
echo "文件 $1 不存在"
return 1
fi
}
# return 0:進(jìn)程沒有運(yùn)行 1:進(jìn)程已運(yùn)行
# @param $1:要監(jiān)控的程序的目錄
function monitor_process() {
if [ $# -ne 1 ]; then
echo "參數(shù)錯誤,正確使用方法: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
}
# 啟動監(jiān)控程序
# @param $1:要監(jiān)控的程序的目錄
function start_monitor() {
if [ $# -ne 1 ]; then
echo "參數(shù)錯誤,正確使用方法: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 "該進(jìn)程沒有運(yùn)行:$process_path"
echo "現(xiàn)將啟動進(jìn)程"
$process_path &
monitor_process $process_name
if [ $? -eq 1 ]; then
echo "重啟進(jìn)程成功"
else
echo "重啟進(jìn)程失敗"
fi
else
echo "進(jìn)程已經(jīng)啟動"
fi
}
# 主程序
# @param $1:要監(jiān)控的程序的目錄
if [ $# -ne 1 ]; then
echo "參數(shù)錯誤,正確使用方法:ecdata_proc_monitor /dir/file"
exit 1
fi
check_file $1
if [ $? -ne 0 ]; then
exit 1
fi
start_monitor $1
4、加上crontab
加上crontab就可以讓腳本定時執(zhí)行,一旦發(fā)現(xiàn)進(jìn)程沒有運(yùn)行,則啟動該進(jìn)程,這樣就實(shí)現(xiàn)了進(jìn)程的自動拉起。
// crontab基本命令
crontab -l #查看任務(wù)
crontab -e #編輯任務(wù)
crontab -r #刪除用戶所有的crontab的內(nèi)容(慎用)
通過crontab -e進(jìn)入類似vim的操作界面,在文件末尾補(bǔ)充*/1 * * * * /root/test/restart.sh /root/test/mycpp&,讓restart.sh腳本每一分鐘運(yùn)行一次(即每分鐘檢測一次mycpp是否正在執(zhí)行)
5、查看結(jié)果
查看mycpp進(jìn)程是否在執(zhí)行 ps -ef | grep mycpp
查看mycpp執(zhí)行寫入的結(jié)果 tail -f myTEXT.txt

查看寫入時間結(jié)果