2012-05-29 124 views
1

我有第三方控制檯應用程序,打印幾行和立即退出(或等待按鍵被關閉 - 取決於使用的參數)。我想從我自己的控制檯程序運行此應用程序,並將其輸出到我的緩衝區。我試過這種方法,但它不起作用:如何閱讀控制檯應用程序的輸出?

....  
HANDLE stdRead, stdWrite; 
SECURITY_ATTRIBUTES PipeSecurity; 
ZeroMemory (&PipeSecurity, sizeof (SECURITY_ATTRIBUTES)); 
PipeSecurity.nLength = sizeof (SECURITY_ATTRIBUTES); 
PipeSecurity.bInheritHandle = true; 
PipeSecurity.lpSecurityDescriptor = NULL; 

CreatePipe (&stdRead, &stdWrite, &PipeSecurity, NULL) 

STARTUPINFO sinfo; 
ZeroMemory (&sinfo, sizeof (STARTUPINFO)); 
sinfo.cb = sizeof (STARTUPINFO); 
sinfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; 
sinfo.hStdInput = stdWrite; 
sinfo.hStdOutput = stdRead; 
sinfo.hStdError = stdRead; 
sinfo.wShowWindow = SW_SHOW; 
CreateProcess (NULL, CommandLine, &PipeSecurity, &PipeSecurity, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &sinfo, &pi)) 

DWORD dwRetFromWait= WAIT_TIMEOUT; 
while (dwRetFromWait != WAIT_OBJECT_0) 
{ 
    dwRetFromWait = WaitForSingleObject (pi.hProcess, 10); 
    if (dwRetFromWait == WAIT_ABANDONED) 
     break; 

    //--- else (WAIT_OBJECT_0 or WAIT_TIMEOUT) process the pipe data 
    while (ReadFromPipeNoWait (stdRead, Buffer, STD_BUFFER_MAX) > 0) 
    { 
     int iLen= 0; //just for a breakpoint, it never breaks here 
    } 
} 
.... 


int ReadFromPipeNoWait (HANDLE hPipe, WCHAR *pDest, int nMax) 
{ 
DWORD nBytesRead = 0; 
DWORD nAvailBytes; 
WCHAR cTmp [10]; 

ZeroMemory (pDest, nMax * sizeof (WCHAR)); 
// -- check for something in the pipe 
PeekNamedPipe (hPipe, &cTmp, 20, NULL, &nAvailBytes, NULL); 
if (nAvailBytes == 0) 
    return (nBytesRead); //always ends here + cTmp contains crap 

// OK, something there... read it 
ReadFile (hPipe, pDest, nMax-1, &nBytesRead, NULL); 

return nBytesRead; 
} 

如果我刪除PeekNamedPipe,它只是掛在ReadFile上,什麼也不做。任何想法可能是錯誤的?管道不是不幸的我的一杯茶,我只是把在互聯網上找到的一些代碼放在一起。

非常感謝。只有當你發現不工作,做一些更復雜的解決您遇到的特定問題(S)

char tmp[1024]; 
std::string buffer; 

FILE *child = _popen("child prog.exe", "r"); 

if (NULL == child) 
    throw std::runtime_error("Unable to spawn child program"); 

while (fgets(tmp, sizeof(tmp), child)) 
    buffer += tmp; 

+0

在命令提示符處輸入'appname> output.txt 2>&1'並查看輸出是否被重定向到文本文件。如果是這樣,你的代碼有問題。否則,你需要一種不同的方法。 – arx

回答

2

我有一個簡單的方法開始。

+0

看起來最簡單的解決方案通常是最好的,謝謝:) – Kra

相關問題