说明: CreateProcess创建进程执行不支持简单的 > 符号重定向,system之类的函数执行外部进程可以使用 > 符号直接重定向到文件,但是system这类函数执行命令时,都会弹出控制台窗口,而CreateProcess创建执行进程可以设置属性隐藏这个控制台窗口,后台执行。
示例代码:
#include<windows.h> #include<shellapi.h> #include<stdio.h> #include <string.h> int my_CreateProcess() { SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; _unlink("D:/output.log"); HANDLE h = CreateFile((L"D:/output.log"), FILE_APPEND_DATA, FILE_SHARE_WRITE | FILE_SHARE_READ, &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); PROCESS_INFORMATION pi; STARTUPINFO si; BOOL ret = FALSE; DWORD flags = CREATE_NO_WINDOW; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = NULL; si.hStdError = h; si.hStdOutput = h; TCHAR cmd[]= TEXT("ipconfig"); ret = CreateProcess(NULL, cmd, NULL, NULL, TRUE, flags, NULL, NULL, &si, &pi); if (ret) { WaitForSingleObject(pi.hProcess, INFINITE); qDebug()<<"执行成功...."; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); //关闭文件 CloseHandle(h); return 0; } //关闭文件 CloseHandle(h); qDebug()<<"执行失败...."; return -1; }