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でハングし、何もしません。何が間違っているのでしょうか?残念ながら、パイプは私のお茶ではありません。インターネットで見つかったコードのいくつかをまとめただけです。

どうもありがとう。

4

1 に答える 1

2

私は簡単なアプローチから始めます:

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;

それがうまくいかないことがわかった場合にのみ、遭遇した特定の問題を解決するためにもっと複雑なことをしてください。

于 2012-05-29T16:25:56.240 に答える