Het onderstaande programma is een voorbeeld van hoe een console-applicatie op te starten, en van hoe de uitvoer van dit programma uit te lezen en weer te geven. Alles gebeurt via de 3 standaard-handles: stdout, stdin en stderr (via Pipes).
#include "stdafx.h"
#include <windows.h>
int main()
{
HANDLE input_PipeRead;
HANDLE input_PipeWrite;
HANDLE output_PipeRead;
HANDLE output_PipeWrite;
HANDLE error_PipeRead;
HANDLE error_PipeWrite;
CHAR message[] = "";
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
SECURITY_ATTRIBUTES security_attributes;
// Set the security attributes for the pipe handles created
security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
security_attributes.bInheritHandle = TRUE;
security_attributes.lpSecurityDescriptor = NULL;
// Create the pipes used for the communication
CreatePipe(&output_PipeRead, &output_PipeWrite, &security_attributes, 0);
CreatePipe(&input_PipeRead, &input_PipeWrite, &security_attributes, 0);
CreatePipe(&error_PipeRead, &error_PipeWrite, &security_attributes, 0);
// Prepare the startup structure for the child process
ZeroMemory(&startup_info, sizeof(STARTUPINFO));
startup_info.cb = sizeof(STARTUPINFO);
startup_info.hStdInput = input_PipeRead;
startup_info.hStdOutput = output_PipeWrite;
startup_info.hStdError = error_PipeWrite;
startup_info.dwFlags = STARTF_USESTDHANDLES;
// Create the child process
if(!CreateProcess(NULL, "cmd /C "echo Test"", NULL, NULL, TRUE, 0, NULL, NULL, &startup_info, &process_info))
return 0;
// Write a message to the child process
if(*message)
{
DWORD bytes_written = 0;
WriteFile(input_PipeWrite, message, strlen(message), &bytes_written, NULL);
}
// Wait for the process to end
WaitForSingleObject(process_info.hProcess, INFINITE);
// Read the message from the child process
DWORD output_BytesToRead = 0, error_BytesToRead = 0;
if( !PeekNamedPipe(output_PipeRead, NULL, 0, NULL, &output_BytesToRead, NULL) || !PeekNamedPipe(error_PipeRead, NULL, 0, NULL, &error_BytesToRead, NULL))
return 0;
CHAR *output_Buffer = new CHAR[output_BytesToRead + 1];
CHAR *error_Buffer = new CHAR[error_BytesToRead + 1];
if(output_Buffer && error_Buffer)
{
DWORD tmp_BytesRead;
// Read the output code
tmp_BytesRead = 0;
if(output_BytesToRead)
ReadFile(output_PipeRead, output_Buffer, output_BytesToRead, &tmp_BytesRead, NULL);
output_Buffer[tmp_BytesRead] = 0;
// Read any errors
tmp_BytesRead = 0;
if(error_BytesToRead)
ReadFile(error_PipeRead, error_Buffer, error_BytesToRead, &tmp_BytesRead, NULL);
error_Buffer[tmp_BytesRead] = 0;
// Output
if(*error_Buffer)
MessageBox(NULL, error_Buffer, "There were errors!", MB_OK);
else
MessageBox(NULL, output_Buffer, "Output code", MB_OK);
}
return 0;
}
09-06-2011, 00:00
Geschreven door Fibergeek 
|