Files
dl_old/dl/system/dl_process.cpp
T
2026-03-26 19:04:23 +08:00

90 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "dl_process.h"
#include <cpp-subprocess/subprocess.hpp>
using namespace subprocess;
#include "memory/dl_code_cvt.h"
#include "io/dl_log.h"
#include "base/dl_string.h"
#include "dl_time.h"
namespace dl
{
bool Process::Exec(const std::vector<std::string>& cmd, Result& result)
{
try
{
Popen p = Popen(cmd, output{ PIPE });
// 等待结束,并读取管道
result._str = p.communicate().first.buf.data();
result._exitCode = p.retcode();
return true;
}
catch (CalledProcessError& e)
{
log_err("创建进程失败{},{}", dl::to_string(cmd), dl::to_string(e.what()));
}
catch (...)
{
log_err0("未知异常!");
}
return false;
}
bool Process::ExecMulti(const std::vector<std::string>& cmd, Instance& instance)
{
try
{
instance._p = new Popen(cmd, output{ PIPE }, input{ PIPE });
}
catch (CalledProcessError& e)
{
log_err("创建进程失败{},{}", dl::to_string(cmd), dl::to_string(e.what()));
}
catch (...)
{
log_err0("未知异常!");
}
instance._thread = g_thread->Create();
instance._thread->Start(_thread_exec, &instance);
return true;
}
void Process::Send(Instance& instance, std::string_view str)
{
instance._p->send(std::string{ str } + '\n');
fflush(instance._p->input());
}
void Process::_thread_exec(void* p)
{
Instance& instance = *(Instance*)p;
while (true)
{
instance._mutexRet.lock();
instance._result._str += Process::_read(instance);
instance._mutexRet.unlock();
g_time->Sleep();
}
}
std::string Process::_read(Instance& instance)
{
char buf[1024];
if (fgets(buf, sizeof(buf), instance._p->output()))
return buf;
else
return {};
}
void Process::Terminate(Instance& instance)
{
instance._p->kill();
instance._thread->Terminate();
}
}