#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));
}
}