Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何读取windows服务启动的控制台应用程序的输出_C++_Windows Services - Fatal编程技术网

C++ 如何读取windows服务启动的控制台应用程序的输出

C++ 如何读取windows服务启动的控制台应用程序的输出,c++,windows-services,C++,Windows Services,我已经创建了一个在LocalSystem帐户中运行的windows服务。在服务中,启动了一个控制台应用程序,我需要在我的windows服务中捕获控制台应用程序的控制台输出 在代码内部,创建了一个用于重定向控制台窗口输出的管道,并将句柄传递给STARTUPINFO以创建控制台应用程序进程。启动控制台应用程序后,代码等待控制台应用程序完成,然后读取控制台应用程序输出。我测试了这个逻辑(类似的代码),如果不是在windows服务中运行的话,它也能正常工作 在我的windows服务中,控制台应用程序是在

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

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

在我的windows服务中,控制台应用程序是在使用登录用户的会话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);
bool-WinProcess::SpawnConsoleProcessAsUser()
{
句柄hToken=NULL;
bool bSuccess=(TRUE==WTSQueryUserToken(m_nSessionId,&hToken));//调用应用程序必须在LocalSystem帐户的上下文中运行
如果(b成功)
{
void*pEnvironment=nullptr;
bSuccess=(TRUE==CreateEnvironmentBlock(&pEnvironment,hToken,TRUE));
如果(b成功)
{
std::wstring strParameters=L“\”+m\u strFullPathExe+L“\”;
对于(size_t i=0;i