Quote Originally Posted by ajbharani
Hi

To take a log of a console application, you have to run the application in a child process which you have to create. After the execution, the details of the execution will be dumped in a readpipe. You have to extract the contents and display. The following piece of code might be helpful for you.

Code:
const int BUFFLENGTH = 255;
 
m_status.SetWindowText("Please wait...");
 
PROCESS_INFORMATION proc;
 
STARTUPINFO start;
 
SECURITY_ATTRIBUTES sa;
 
HANDLE hReadPipe,hWritePipe;
 
//fill memory with zeros
 
ZeroMemory(&start,sizeof(start));
 
//initialize security attributes
 
sa.bInheritHandle=TRUE;
 
sa.nLength=sizeof(sa);
 
sa.lpSecurityDescriptor=NULL;
 
 
 
//fill memory with zeros
 
ZeroMemory(&proc,sizeof(proc));
 
 
 
//create pipe with read and write handles
 
if(!CreatePipe(&hReadPipe,&hWritePipe,&sa,0))
 
{
 
MessageBox("Cannot create pipe");
 
m_status.SetWindowText("Cannot create pipe");
 
return;
 
}
 
//init start
 
start.cb=sizeof(start);
 
start.dwFlags = STARTF_USESTDHANDLES;
 
start.hStdOutput = hWritePipe;
 
start.hStdError = hWritePipe;
 
start.wShowWindow = SW_HIDE;
 
char pPath[255];
 
m_process.GetWindowText(pPath,255);
 
if(!CreateProcess(NULL,pPath,&sa,&sa,TRUE,NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW,NULL,NULL,&start,&proc))
 
{
 
MessageBox("Cannot create process");
 
m_status.SetWindowText("Cannot create process");
 
return;
 
}
 
CString outputText;
 
//close handles
 
CloseHandle(hWritePipe);
 
//produce log
 
DWORD bytesread;
 
BOOL bSuccess;
 
int bytestoread = BUFFLENGTH;
 
char mybuff[BUFFLENGTH]="";
 
do 
 
{
 
bSuccess = 0;
 
strcpy(mybuff,"");
 
bSuccess = ReadFile(hReadPipe,mybuff, bytestoread, &bytesread, NULL);
 
if (bSuccess && bytesread)
 
{
 
for(unsigned int i=0; i<bytesread; i++)
 
{
 
outputText += mybuff[i];
 
}
 
}
 
}
 
while (bytesread && bSuccess);
 
 
 
DWORD WaitReturnCode;
 
WaitReturnCode=WaitForSingleObject(proc.hProcess,INFINITE);
 
m_status.SetWindowText("");
 
 
 
//return status
 
switch(WaitReturnCode)
 
{
 
case WAIT_ABANDONED:
 
MessageBox("Process Abandoned");
 
m_status.SetWindowText("Process Abandoned");
 
break;
 
case WAIT_OBJECT_0:
 
m_status.SetWindowText("Process completed");
 
break;
 
case WAIT_TIMEOUT:
 
MessageBox("Process timedout");
 
m_status.SetWindowText("Process Timedout");
 
break;
 
default:
 
;
 
}
 
//close remaining handles
 
CloseHandle(hReadPipe);
 
CloseHandle(proc.hThread);
 
CloseHandle(proc.hProcess);
 
//generate log file for the operation
 
char lPath[255];
 
m_log.GetWindowText(lPath,255);
 
CFile logFile;
 
logFile.Open(lPath,CFile::modeCreate|CFile::modeWrite);
 
logFile.Write(outputText,outputText.GetLength());
 
logFile.Close();


This is actually a part of an MFC application which creates a process and generates a log. The string pPath is the path of the console application executable. And the string lPath is the path of your log file.
Thanks !