进程监控程序,死掉了自动重启

该程序用于监测一组指定的进程,如果发现某个进程未运行,则会启动一个新的进程实例。它使用fork、execl系统调用来创建和执行进程,通过pidof检查进程状态,并通过命令行参数接收进程路径和名称。
摘要由CSDN通过智能技术生成

#include
#include
#include
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include
#include
#include
#include <sys/wait.h>
#include
#include<sys/stat.h>
#include<sys/types.h>

using namespace std;

void start_process(string process_name, string process_path)
{
pid_t pid = fork();

if (pid == 0)
{
    // 在子进程中启动新的进程
    int result = execl((process_path + "/" + process_name).c_str(), process_name.c_str(), NULL);
    if (result == -1)
    {
        cout << "无法启动 " << process_name << ", 错误信息:" << strerror(errno) << endl;
    }
    exit(0);
}
else if (pid < 0)
{
    // 出错处理
    cout << "无法启动 " << process_name << ", 错误信息:" << strerror(errno) << endl;
}

}

int main(int argc, char *argv[])
{
// 解析命令行参数
vector process_paths;
vector process_names;

将参数解析为进程路径和进程名称
for (int i = 1; i < argc; i++)
{
string arg = argv[i];
stringstream ss(arg);
string item;
int count = 0;
while (getline(ss, item, ‘,’))
{
if (count == 0)
{
process_paths.push_back(item);

        }
        else {
            process_names.push_back(item);

        }
        count++;
    }
}


while (true)
{

    // 循环遍历每个进程并检查其运行状态
    for (int i = 0; i < process_names.size(); i++)
    {
        string process_name = process_names[i];
        string process_path = process_paths[i];
        // 检查进程是否正在运行

        string command = "pidof " + process_path + "/" + process_name;
        FILE *fp = popen(command.c_str(), "r");
        char buf[1024] = {0};
        fgets(buf, 1024, fp);
        pclose(fp);

        if (strlen(buf) > 0)
        {
            cout << "进程 " << process_name << " 正在使用pid运行:" << buf << endl;
            continue;
        }
        else
            {
            cout << "进程 " << process_name << "没有运行。正在启动新实例。" << endl;
            // 启动新的进程
            start_process(process_name, process_path);
            }
    }
    //检测间隔
    this_thread::sleep_for(chrono::seconds(2));
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起个网名真难~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值