gpt4 book ai didi

c++ - 如何读取 Windows 服务启动的控制台应用程序的输出

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:18 25 4
gpt4 key购买 nike

我创建了一个在 LocalSystem 帐户中运行的 Windows 服务。在该服务中,启动了一个控制台应用程序,我需要在我的 Windows 服务中捕获控制台应用程序的控制台输出。

在代码中,创建了一个用于重定向控制台窗口输出的管道,并将句柄传递给用于创建控制台应用程序进程的 STARTUPINFO。控制台应用程序启动后,代码等待控制台应用程序完成,然后读取控制台应用程序输出。如果不在 Windows 服务中运行,我测试了这个逻辑(类似的代码)。

在我的 Windows 服务中,控制台应用程序是在使用登录用户的 session ID 创建的环境中启动的。我可以看到控制台应用程序已启动,并在控制台窗口中输出文本。但是在控制台应用程序完成后,我的 Windows 服务没有读取任何控制台输出文本。

我的问题是我想达到的目标能实现吗?如果是这样,我在下面的代码中缺少什么?

bool WinProcess::SpawnConsoleProcessAsUser()
{
HANDLE hToken = NULL;
bool bSuccess = (TRUE == WTSQueryUserToken(m_nSessionId, &hToken)); // calling application must be running within the context of the LocalSystem account
if (bSuccess)
{
void* pEnvironment = nullptr;
bSuccess = (TRUE == CreateEnvironmentBlock(&pEnvironment, hToken, TRUE));
if (bSuccess)
{
std::wstring strParameters = L"\"" + m_strFullPathExe + L"\" ";
for (size_t i = 0; i < m_vecParams.size(); ++i)
{
strParameters += m_vecParams[i] + L" ";
}

wchar_t cBuf[1024];
ZeroMemory(cBuf, sizeof(cBuf));
swprintf_s(cBuf, _countof(cBuf), strParameters.c_str());

// Create security attributes to create pipe.
SECURITY_ATTRIBUTES oSecurity = { sizeof(SECURITY_ATTRIBUTES) };
oSecurity.bInheritHandle = TRUE; // Set the bInheritHandle flag so pipe handles are inherited by child process. Required.
oSecurity.lpSecurityDescriptor = NULL;

m_hChildStdOutRead = NULL;
m_hChildStdOutWrite = NULL;;

// Create a pipe to get results from child's stdout.
// I'll create only 1 because I don't need to pipe to the child's stdin.
bool bSuccess = (TRUE == CreatePipe(&m_hChildStdOutRead, &m_hChildStdOutWrite, &oSecurity, 0));
if (bSuccess)
{
ZeroMemory(&m_oStartupInfo, sizeof(m_oStartupInfo));
m_oStartupInfo.cb = sizeof(m_oStartupInfo);
m_oStartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; // STARTF_USESTDHANDLES is Required.
m_oStartupInfo.hStdOutput = m_hChildStdOutWrite; // Requires STARTF_USESTDHANDLES in dwFlags.
m_oStartupInfo.hStdError = m_hChildStdOutWrite; // Requires STARTF_USESTDHANDLES in dwFlags.
// m_oStartupInfo.hStdInput remains null.
#if 0
m_oStartupInfo.wShowWindow = SW_HIDE;
#else
m_oStartupInfo.wShowWindow = SW_SHOW;
#endif
m_oStartupInfo.lpDesktop = L"winsta0\\default";

PROCESS_INFORMATION oProcessInfo;
ZeroMemory(&oProcessInfo, sizeof(oProcessInfo));

bSuccess = (TRUE == CreateProcessAsUser(hToken, // primary token representing a user
m_strFullPathExe.c_str(), // optional application name
cBuf, // command line
NULL, // process attributes
NULL, // thread attributes
FALSE, // inherit handles
NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT
| CREATE_NEW_CONSOLE, // creation flags
pEnvironment, // environment block
m_strWorkingDir.c_str(), // starting directory
&m_oStartupInfo, // startup info
&oProcessInfo)); // process info

DestroyEnvironmentBlock(pEnvironment);
CloseHandle(hToken);
if (bSuccess)
{
m_hChildProcess = oProcessInfo.hProcess;
m_hChildThread = oProcessInfo.hThread;
}
}
if (!bSuccess)
{
DWORD dwError = GetLastError();
ErrorReport(TEXT(__FUNCTION__), dwError);
}
}
else
{
CloseHandle (hToken);
}
}
return bSuccess;
}

bool WinProcess::WaitFinish(const uint32_t a_unTimeoutMs)
{
static const wchar_t CR = L'\r';
DWORD dwTimeoutMs = a_unTimeoutMs;
if (UINT_MAX == a_unTimeoutMs)
{
dwTimeoutMs = INFINITE;
}
time_t tStart;
time(&tStart);
DWORD dwCode = WaitForSingleObject(m_hChildProcess, dwTimeoutMs);
bool bSuccess = (WAIT_TIMEOUT != dwCode);
if (!bSuccess)
{
// timed out waiting for the termination of the net command process
bSuccess = (FALSE != TerminateProcess(m_hChildProcess, WAIT_FAILED));
}
else
{
DWORD dwExitCode = STILL_ACTIVE;
if (FALSE == GetExitCodeProcess(m_hChildProcess, &dwExitCode))
{
// logging her
}
else if (STILL_ACTIVE == dwExitCode)
{
// logging her
}
else
{
time_t tDone;
time(&tDone);
bSuccess = (0 == dwExitCode);
}
m_nExitCode = dwExitCode;

CloseHandle(m_hChildProcess);
if (NULL != m_hChildThread)
{
CloseHandle(m_hChildThread);
}
}
CloseHandle(m_hChildStdOutWrite);

m_bTerminated = true;
m_strProcessOutput = ReadProcessOutput();
m_strProcessOutput.erase(std::remove(m_strProcessOutput.begin(), m_strProcessOutput.end(), CR), m_strProcessOutput.end());

return bSuccess;
}

std::wstring WinProcess::ReadProcessOutput()
{
std::string strProcessOut("");
for (;;)
{
DWORD dwRead;
char cBuf[1024];

// Read from pipe that is the standard output for child process.
ZeroMemory(cBuf, sizeof(cBuf));
bool bDone = !ReadFile(m_hChildStdOutRead, cBuf, sizeof(cBuf) - 1, &dwRead, NULL) || dwRead == 0;
if (bDone)
{
break;
}
cBuf[dwRead] = '\0';

// Append result to string.
strProcessOut += std::string(cBuf);
}
return StrUtil::string_cast<std::wstring>(strProcessOut);

最佳答案

我从另一个论坛得到了答案。 “继承句柄”应设置为 TRUE。

关于c++ - 如何读取 Windows 服务启动的控制台应用程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58534827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com