我有一个 MFC 应用程序,它通过CreateProcess函数向 cmd 发送命令。我想将标准输出放入日志文件。代码是这样的
void CMainFrame::OnCompile( CString cmd )
{
CWaitCursor cursor;
SECURITY_ATTRIBUTES sec;
ZeroMemory( &sec, sizeof(sec) );
sec.nLength = sizeof(SECURITY_ATTRIBUTES);
sec.lpSecurityDescriptor = NULL;
sec.bInheritHandle = TRUE;
HANDLE hstdoutf = CreateFile("e:\\user_stdout.txt",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,&sec,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
STARTUPINFO siStartupInfo;
PROCESS_INFORMATION piProcessInfo;
memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));
siStartupInfo.cb = sizeof(siStartupInfo);
siStartupInfo.dwFlags = STARTF_USESHOWWINDOW ;
siStartupInfo.wShowWindow = SW_HIDE;
if (hstdoutf!=INVALID_HANDLE_VALUE) {
siStartupInfo.hStdOutput=hstdoutf;
}
// Wait up to 100 seconds for the compilation process to finish
if (!::CreateProcess(0, (char*)(cmd.GetString()), 0, 0, false,0, 0, 0,
&siStartupInfo, &piProcessInfo) ||
(WaitForSingleObject(piProcessInfo.hProcess, 100000) != WAIT_OBJECT_0))
{
MessageBox("Fail to execute command","Test",MB_ICONERROR);
}
else
{
CloseHandle(hstdoutf);
}
}
但代码无法正常工作。仅创建一个空白文件。我做错了什么?请帮忙。