CreateProcess()输出到文件

利用CreateProcess()创建子进程,并输出到文件,主要步骤如下:

//首先用CreateFile创建文件,得到文件句柄。 HANDLE hFile = CreateFile(m_sAllPath.c_str(),GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ,&sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("Could not open file (error %d)/n", GetLastError()); return 0; } printf("CreateFile success/n"); STARTUPINFO si; PROCESS_INFORMATION pi; LPTSTR szCmdLine = const_cast<LPTSTR>(sTotalCmd.c_str()); //然后将子进程的标准输出重定向到刚刚创建的文件句柄。 HANDLE hTemp = GetStdHandle(STD_OUTPUT_HANDLE); SetStdHandle(STD_OUTPUT_HANDLE, hFile);// 设置标准输出 GetStartupInfo(&si); // 获取本进程的STARTUPINFO结构信息 ZeroMemory( &pi, sizeof(pi) ); // Start the child process. if( !CreateProcess( NULL, // No module name (use command line) szCmdLine, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block m_sBinDir.c_str(), // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { printf( "CreateProcess failed (%d)./n", GetLastError() ); return 0; } printf("CreateProcess success/n"); WaitForSingleObject( pi.hProcess, INFINITE );// Wait until child process exits. // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); CloseHandle(hFile); // 最后恢复本进程的标准输出 SetStdHandle(STD_OUTPUT_HANDLE, hTemp);

你可能感兴趣的:(CreateProcess()输出到文件)