Files
dl_old/dl/system/dl_process.cpp
T
2024-05-14 19:01:57 +08:00

112 lines
3.4 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"
#if DL_PLATFORM == DL_PLATFORM_WIN32
#include <windows.h>
#include "memory/dl_code_cvt.h"
#include "io/dl_log.h"
namespace dl
{
bool Process::Exec(std::string_view exe, std::string_view cmd,
Result* result, ExecMultiData* data)
{
std::wstring str_exe = dl::CodeCvt::Utf8ToWideChar(exe);
std::wstring str_cmd = dl::CodeCvt::Utf8ToWideChar(cmd);
//----------------------创建管道--------------------
SECURITY_ATTRIBUTES la; // 管道的安全属性
la.nLength = sizeof(la); // 大小
la.bInheritHandle = TRUE; // 可以被继承
la.lpSecurityDescriptor = NULL; // 安全描述符为默认
// 创建匿名管道,默认大小
HANDLE h_pread, h_pwrite;
if (!CreatePipe(&h_pread, &h_pwrite, &la, 4096))
{
log_err("创建管道失败!");
return false;
}
//----------------------创建线程--------------------
STARTUPINFOW si{}; // 开始信息
PROCESS_INFORMATION pi{}; // 进程信息
si.cb = sizeof(STARTUPINFOW);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = NULL; //GetStdHandle(STD_INPUT_HANDLE)
si.hStdError = h_pwrite;
si.hStdOutput = h_pwrite;
log_info("创建新进程:{},{}", exe, cmd);
if (!CreateProcessW(
str_exe.c_str(), // 指向一个NULL结尾的、用来指定可执行模块的宽字节字符串
str_cmd.data(), // 命令行字符串
NULL, // 指向一个SECURITY_ATTRIBUTES结构体,这个结构体决定是否返回的句柄可以被子进程继承。
NULL, // 如果lpProcessAttributes参数为空(NULL),那么句柄不能被继承。<同上>
TRUE,// 指示新进程是否从调用进程处继承了句柄。
CREATE_NO_WINDOW, // 指定附加的、用来控制优先类和进程的创建的标
// CREATE_NEW_CONSOLE 新控制台打开子进程
// CREATE_SUSPENDED 子进程创建后挂起,直到调用ResumeThread函数
NULL, // 指向一个新进程的环境块。如果此参数为空,新进程使用调用进程的环境
NULL, // 指定子进程的工作路径
&si, // 决定新进程的主窗体如何显示的STARTUPINFO结构体
&pi // 接收新进程的识别信息的PROCESS_INFORMATION结构体
))
{
log_err("创建进程失败!");
return false;
}
// 记录进程句柄
if (data)
{
data->_handle = pi.hProcess;
}
Buffer buf;
TCHAR szBuff[4096] = {}; // 读取管道中的数据放到这个数组中,4k的大小
DWORD dwRead; // 实际读到的个数
DWORD exit_code;
// 直接关闭write
if (h_pwrite != NULL)
{
CloseHandle(h_pwrite);
h_pwrite = NULL;
}
while (ReadFile(h_pread, szBuff, 4096, &dwRead, NULL))
{
// 累加数据
dl::BufferAppend(buf, { (std::byte*)szBuff , dwRead });
memset(szBuff, 0, sizeof(szBuff));
}
WaitForSingleObject(pi.hProcess, INFINITE);
GetExitCodeProcess(pi.hProcess, &exit_code);
if (result)
{// 记录结果
result->_exitCode = (int)exit_code;
buf.push_back((std::byte)0);
result->_log = dl::CodeCvt::MultiByteToUtf8((char*)buf.data());
log_msg("{}", result->_log);
log_msg("进程返回({}):", result->_exitCode);
}
CloseHandle(h_pread); // 关闭管道的读
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return true;
}
void Process::Terminate(ExecMultiData* data)
{
TerminateProcess(data->_handle, 0);//终止进程
data->_thread->Terminate();
}
}
#endif