116 lines
2.2 KiB
C++
116 lines
2.2 KiB
C++
#include "dl_process.h"
|
||
|
||
#include <subprocess.h>
|
||
|
||
#include "memory/dl_code_cvt.h"
|
||
#include "io/dl_log.h"
|
||
#include "base/dl_string.h"
|
||
|
||
namespace dl
|
||
{
|
||
bool Process::Exec(const std::vector<std::string>& cmd, Result* result)
|
||
{
|
||
if (cmd.size() >= 64)
|
||
{
|
||
log_err("命令行参数过多,最多63个!");
|
||
return false;
|
||
}
|
||
const char* p_cmd[64] = {};
|
||
size_t i = 0;
|
||
for (; i < cmd.size(); ++i)
|
||
{
|
||
p_cmd[i] = cmd[i].c_str();
|
||
}
|
||
|
||
|
||
subprocess_s p;
|
||
int rc = subprocess_create(p_cmd, 0, &p);
|
||
if (0 != rc)
|
||
{
|
||
log_err("创建进程失败[{}]:{}", rc, dl::to_string(cmd));
|
||
return false;
|
||
}
|
||
|
||
int process_return;
|
||
rc = subprocess_join(&p, &process_return);
|
||
if (0 != rc)
|
||
{
|
||
log_err("执行进程失败[{}]:{}", rc, dl::to_string(cmd));
|
||
return false;
|
||
}
|
||
|
||
if (result)
|
||
{
|
||
result->_exitCode = process_return;
|
||
|
||
FILE* p_stdout = subprocess_stdout(&p);
|
||
|
||
while (true)
|
||
{
|
||
char buf[1024];
|
||
char* c = fgets(buf, 1024, p_stdout);
|
||
if (c == nullptr)
|
||
break;
|
||
result->_log += buf;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
bool Process::ExecMulti(const std::vector<std::string>& cmd, Instance* instance)
|
||
{
|
||
if (cmd.size() >= 64)
|
||
{
|
||
log_err("命令行参数过多,最多63个!");
|
||
return false;
|
||
}
|
||
const char* p_cmd[64] = {};
|
||
size_t i = 0;
|
||
for (; i < cmd.size(); ++i)
|
||
{
|
||
p_cmd[i] = cmd[i].c_str();
|
||
}
|
||
|
||
instance->_p = new subprocess_s;
|
||
int rc = subprocess_create(p_cmd, 0, (subprocess_s*)instance->_p);
|
||
if (0 != rc)
|
||
{
|
||
log_err("创建进程失败[{}]:{}", rc, dl::to_string(cmd));
|
||
return false;
|
||
}
|
||
|
||
instance->_thread = g_thread->Create();
|
||
instance->_thread->Start(_thread_exec, instance);
|
||
|
||
return true;
|
||
}
|
||
|
||
void Process::Write(Instance* instance, std::string_view str)
|
||
{
|
||
FILE* p_stdin = subprocess_stdin((subprocess_s*)instance->_p);
|
||
fputs(str.data(), p_stdin);
|
||
fflush(p_stdin);
|
||
}
|
||
|
||
std::string Process::Read(Instance* instance)
|
||
{
|
||
FILE* p_stdout = subprocess_stdout((subprocess_s*)instance->_p);
|
||
std::string ret;
|
||
while (true)
|
||
{
|
||
char buf[1024];
|
||
char* c = fgets(buf, 1024, p_stdout);
|
||
if (c == nullptr)
|
||
break;
|
||
ret += buf;
|
||
}
|
||
return ret;
|
||
}
|
||
|
||
void Process::Terminate(Instance* data)
|
||
{
|
||
//TerminateProcess(data->_p, 0);//终止进程
|
||
data->_thread->Terminate();
|
||
}
|
||
}
|