数行を出力してすぐに終了する(またはキーが押されるのを待つ-使用する引数によって異なります)サードパーティのコンソールアプリがあります。このアプリケーションを自分のコンソールプログラムから実行し、その出力をバッファに入れたいと思います。私はこのアプローチを試しましたが、機能しません:
....
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でハングし、何もしません。何が間違っているのでしょうか?残念ながら、パイプは私のお茶ではありません。インターネットで見つかったコードのいくつかをまとめただけです。
どうもありがとう。