master
cpp 77 lines 2.33 KB
Raw
1 /*++
2
3 Copyright (c) Microsoft. All rights reserved.
4
5 Module Name:
6
7 ServiceProcessLauncher.cpp
8
9 Abstract:
10
11 This file contains the implementations of ServiceProcessLauncher and ServiceRunningProcess.
12
13 --*/
14
15 #include "ServiceProcessLauncher.h"
16 #include "WSLCVirtualMachine.h"
17
18 using wsl::windows::service::wslc::ServiceProcessLauncher;
19 using wsl::windows::service::wslc::ServiceRunningProcess;
20 using wsl::windows::service::wslc::WSLCProcess;
21
22 ServiceRunningProcess::ServiceRunningProcess(const Microsoft::WRL::ComPtr<WSLCProcess>& process, WSLCProcessFlags flags) :
23 common::RunningWSLCProcess(flags)
24 {
25 process.CopyTo(m_process.GetAddressOf());
26 }
27
28 wsl::windows::common::io::HandleWrapper ServiceRunningProcess::GetStdHandle(int Index)
29 {
30 return Get().GetStdHandle(Index);
31 }
32
33 wil::unique_event ServiceRunningProcess::GetExitEvent()
34 {
35 // Unlike for std handles, the event handle needs to be duplicated, since we need to keep a reference to it
36 // to signal it once the process exits.
37 wil::unique_event event;
38 THROW_IF_WIN32_BOOL_FALSE(
39 DuplicateHandle(GetCurrentProcess(), m_process->GetExitEvent(), GetCurrentProcess(), &event, SYNCHRONIZE, false, 0));
40
41 return event;
42 }
43
44 WSLCProcess& ServiceRunningProcess::Get()
45 {
46 return *m_process.Get();
47 }
48
49 void ServiceRunningProcess::GetState(WSLCProcessState* State, int* Code)
50 {
51 THROW_IF_FAILED(m_process->GetState(State, Code));
52 }
53
54 std::tuple<HRESULT, int, std::optional<ServiceRunningProcess>> ServiceProcessLauncher::LaunchNoThrow(WSLCVirtualMachine& virtualMachine)
55 {
56 auto [options, commandLine, env] = CreateProcessOptions();
57 int error = -1;
58
59 std::optional<ServiceRunningProcess> process;
60 auto result = wil::ResultFromException([&]() {
61 process.emplace(virtualMachine.CreateLinuxProcess(m_executable.c_str(), options, m_rows, m_columns, &error), m_flags);
62 });
63
64 return {result, error, std::move(process)};
65 }
66
67 ServiceRunningProcess ServiceProcessLauncher::Launch(WSLCVirtualMachine& virtualMachine)
68 {
69 auto [hresult, error, process] = LaunchNoThrow(virtualMachine);
70 if (FAILED(hresult))
71 {
72 auto commandLine = wsl::shared::string::Join(m_arguments, ' ');
73 THROW_HR_MSG(hresult, "Failed to launch process: %hs (commandline: %hs). Errno = %i", m_executable.c_str(), commandLine.c_str(), error);
74 }
75
76 return std::move(process.value());
77 }