Hi!
I've got this code that pipes the console output into a string. The problem is that when I use it in a DLL file, and use this DLL file from VB, the console's output is not in the string, as it should be. It executes but does not store the output into the string.
Any ideas?
Here is my code:
Code:
std::string ConsoleInfo(LPSTR Command)
{
std::string result;
HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, hSaveStdout;
SECURITY_ATTRIBUTES saAttr;
BOOL fSuccess;
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Save the handle to the current STDOUT.
hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Create a pipe for the child process's STDOUT.
if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
return result;
// Set a write handle to the pipe to be STDOUT.
if (! SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr))
return result;
// Create noninheritable read handle and close the inheritable read handle.
fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
GetCurrentProcess(), &hChildStdoutRdDup , 0,
FALSE,
DUPLICATE_SAME_ACCESS);
if( !fSuccess )
return result;
CloseHandle(hChildStdoutRd);
// Now create the child process.
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
// Create the child process.
fSuccess = CreateProcess(NULL,
Command, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
if (! fSuccess)
return result;
// After process creation, restore the saved STDIN and STDOUT.
if (! SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout))
return result;
// Read from pipe that is the standard output for child process.
DWORD dwRead;
CHAR chBuf[4096];
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Close the write end of the pipe before reading from the
// read end of the pipe.
if (!CloseHandle(hChildStdoutWr))
return result;
// Read output from the child process, and write to parent's STDOUT.
for (;;)
{
if( !ReadFile(hChildStdoutRdDup, chBuf, 4096, &dwRead, NULL) || dwRead == 0)
break;
result += chBuf;
}
return result;
}
Thanks!