如何从控制台启动可执行文件并使用Qt读取输出

时间:2019-07-17 06:44:22

标签: c++ qt winapi windows-ce qprocess

我想从cmd上的Qt启动可执行文件,然后读取其输出。

我必须为此使用WinAPI吗?例如CreateProcess()?

我使用了QProcess,它在Windows 10上可以正常工作,但是不适用于Windows CE。这是在台式机上运行的示例代码;

    QProcess p;
    p.start(path, arg);
    p.waitForFinished();
    std::string output = p.readAll();

2 个答案:

答案 0 :(得分:0)

QT 4.8 documentation状态

Note: On Windows CE and Symbian, reading and writing to a process is not supported.

答案 1 :(得分:0)

尝试此类(省略了一些错误检查)

#pragma once
#include <windows.h>
#include <thread>
#include <iostream>
#include <sstream>
#define BUFSIZE 4096
class m_Process
{
public:
    m_Process();
    ~m_Process();
    BOOL start(char* path, char* cmd);
    void waitForFinished();
    std::string readAll();

private:
    HANDLE hProcess;
    HANDLE hRead;
    HANDLE hWrite;
    std::ostringstream stream;
    friend void ReadFromPipe(m_Process* Process);
};

void ReadFromPipe(m_Process* Process)
{
    DWORD dwRead;
    CHAR chBuf[BUFSIZE];
    BOOL bSuccess = FALSE;
    Process->stream.clear();
    for (;;)
    {
        bSuccess = ReadFile(Process->hRead, chBuf, BUFSIZE-1, &dwRead, NULL);
        if (!bSuccess || dwRead == 0) break;
        chBuf[dwRead] = 0;
        Process->stream << chBuf;
    }
}

m_Process::m_Process()
{
    hProcess = NULL;
    SECURITY_ATTRIBUTES saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;
    CreatePipe(&hRead, &hWrite, &saAttr, 0);
    SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
}


m_Process::~m_Process()
{
    if(hRead)
        CloseHandle(hRead);
    if (hWrite)
        CloseHandle(hWrite);
    CloseHandle(hProcess);
    stream.clear();
}

BOOL m_Process::start(char * path, char * cmd)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    si.dwFlags = STARTF_USESTDHANDLES;
    si.wShowWindow = TRUE;
    si.hStdOutput = hWrite;
    si.hStdError = hWrite;
    BOOL ret = CreateProcess(path, cmd, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi);
    CloseHandle(hWrite);
    hWrite = NULL;
    std::thread t(&ReadFromPipe,this);
    t.join();
    if (ret)
        hProcess = pi.hProcess;
    return ret;
}

void m_Process::waitForFinished()
{
    if (hProcess)
        WaitForSingleObject(hProcess, INFINITE);
}

std::string m_Process::readAll()
{
    return stream.str();
}

用法:

m_Process p;
p.start(path, arg);
p.waitForFinished();
std::string output = p.readAll();