前一篇文章讲过如何隐藏控制台窗口,并把结果返回。但是控制台有个输出重定向输出到文件功能,这个在createprocess中是不支持的。因此那个函数改进如下
TCHAR strLog[1024]={0};
CString strCmp =_T("test.exe abc>abc.h");
RunCMD(strLog,strCmp.GetBuffer(),TRUE);//这个是用法
BOOL RunCMD(TCHAR *pLog,TCHAR *pCmd,BOOL bReconstruct)//最后这个参数说明是否重定向到文件
{
SECURITY_ATTRIBUTES sa;
BOOL ret;
sa.nLength=256;
sa.lpSecurityDescriptor=0;
sa.bInheritHandle=TRUE;
HANDLE hReadPipe1,hWritePipe1,hReadPipe2,hWritePipe2;
HANDLE hOpenFile;
CString strReconstruct;
////////////
_SECURITY_ATTRIBUTES sec;
sec.bInheritHandle=TRUE;//这个东西不添加就不会写入文件 解决运行完毕但是文件为空的问题
sec.lpSecurityDescriptor=NULL;//这个东西不添加就会返回998
/////////////
ret=CreatePipe(&hReadPipe2,&hWritePipe2,&sa,0);
if(bReconstruct)
{
strReconstruct = pCmd;
strReconstruct = strReconstruct.Right(strReconstruct.GetLength()-strReconstruct.ReverseFind('>')-1);
hOpenFile = (HANDLE)CreateFile(strReconstruct.GetBuffer(), GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ,&sec, CREATE_NEW,NULL, NULL);
if (hOpenFile == INVALID_HANDLE_VALUE)
{
int iRes = GetLastError();
hOpenFile = NULL;
return FALSE;
}
}
else
{
ret=CreatePipe(&hReadPipe1,&hWritePipe1,&sa,0);//创建两个匿名管道
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si,sizeof(si));
si.cb = sizeof(si);
si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow=SW_HIDE;
si.hStdInput=hReadPipe2;
if(bReconstruct)
{
si.hStdOutput=si.hStdError=hOpenFile;
}
else
{
si.hStdOutput=si.hStdError=hWritePipe1;
}
ZeroMemory( &pi,sizeof(pi));
unsigned long lBytesRead;
char Buff[1024]={0};
CString strLog;
CreateProcess(NULL,pCmd,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
while(1&&!bReconstruct)
{
ret=PeekNamedPipe(hReadPipe1,Buff,1024,&lBytesRead,0,0);//管道是否有数据可读
if(lBytesRead&&pLog)
{
ret=ReadFile(hReadPipe1,Buff,lBytesRead,&lBytesRead,0);//读取管道里的数据
strLog.Format(_T("%S"),Buff);
StrCpy(pLog,strLog.GetBuffer());
if(!ret)
break;
}
else
break;
}
if(bReconstruct)
{
CloseHandle(hOpenFile);
}
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return TRUE;
}