I have a 3rd party console app that prints few lines and immediatelly quits (or waits for a key to be pressed to be closed - depends on used arguments). I would like to run this application from my own console program and get its output into my buffer. I've tried this approach but it doesn't work:
....
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;
}
If I remove PeekNamedPipe, it just hangs on ReadFile and does nothing. Any ideas what may be wrong? Pipes aren't unfortunately my cup of tea, I've just put together some of the code found on the Internet.
Thanks a lot.
appname > output.txt 2>&1and see if the output is redirected to the text file. If it is, there's something wrong with your code. Otherwise you'll need a different approach.