用户可以在主线程中调用ServerManager来启动某个command触发的进程
#ifndef YOUR_OWN_SERVERMANAGER_H
#define YOUR_OWN_SERVERMANAGER_H
#include <string>
#include <thread>
class ServerManager
{
public:
ServerManager() = default;
~ServerManager(){}
void start(const std::string& cmd);
private:
std::jthread t_;
};
#endif // YOUR_OWN_SERVERMANAGER_H
比较有意思的地方在于这里用到了boost::process 之前没有看到过这么有意思的用法,可以单独传入环境变量。
某些特殊场景可能用该方式比较合适
#include "ServerManager.h"
#include <stdlib.h>
#include <boost/process.hpp>
#include <thread>
namespace bp = boost::process;
void ServerManager::start(const std::string &cmd)
{
auto thread_func = [](std::string command)
{
auto env = boost::this_process::environment();
env["PATH"] = "/usr/bin:/usr/sbin";
bp::child childprocess(command, env);
// TODO: active supervise child and terminate it if no response
childprocess.wait();
auto result = childprocess.exit_code();
//add log here
};
t_ = std::jthread{thread_func, cmd};
}