#include "process.hpp"
namespace win32
{
process::process(const std::string& executable_path, const std::string& command_line_args, process_creation_flags flags)
{
std::copy(std::begin(command_line_args), std::end(command_line_args), std::back_inserter(cmdline));
cmdline.push_back('\0');
STARTUPINFOA startup_info;
GetStartupInfoA(&startup_info);
if (!CreateProcessA(executable_path.c_str(), cmdline.data(), nullptr, nullptr, false, static_cast<DWORD>(flags), nullptr, nullptr, &startup_info, &process_info))
{
throw std::runtime_error("process creation failed!");
}
}
process::process(process &&other) noexcept : cmdline{ std::move(other.cmdline) }, process_info{ other.process_info }
{
other.process_info.hThread = INVALID_HANDLE_VALUE;
other.process_info.hProcess = INVALID_HANDLE_VALUE;
}
process & process::operator=(process &&other) noexcept
{
terminate();
cmdline = std::move(other.cmdline);
process_info = other.process_info;
other.process_info.hThread = INVALID_HANDLE_VALUE;
other.process_info.hProcess = INVALID_HANDLE_VALUE;
return *this;
}
void process::terminate(int exit_code)
{
if (process_info.hThread != INVALID_HANDLE_VALUE)
{
TerminateThread(process_info.hThread, 0exit_code);
CloseHandle(process_info.hThread);
process_info.hThread = INVALID_HANDLE_VALUE;
}
if (process_info.hProcess != INVALID_HANDLE_VALUE) {
TerminateProcess(process_info.hProcess, 0exit_code);
CloseHandle(process_info.hProcess);
process_info.hProcess = INVALID_HANDLE_VALUE;
}
}
process::~process() noexcept
{
terminate();
}
}