rd
像,和 ... 之类的一些系统命令del
不是实际的可执行映像(例如 .exe 文件),因此您不能使用CreateProcess
它们是已知的内置命令cmd
(Windows 命令解释器)来执行/运行它们,因此您应该创建cmd
并将您的命令传递给它:
wchar_t cmd[ MAX_PATH ];
size_t nSize = _countof(cmd);
_wgetenv_s( &nSize, cmd, L"COMSPEC" );
BOOL b = CreateProcessW( cmd, input, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &startInf, &procInf );
注意:请参阅 的参数cmd
,您必须使用它/C
来传递您的命令。所以你的命令如下:
wchar_t input[] = L"some command";
wchar_t cmd[MAX_PATH] ;
// initialize cmd
wchar_t cmdline[ MAX_PATH + 50 ];
swprintf_s( cmdline, L"%s /c %s", cmd, input );
STARTUPINFOW startInf;
memset( &startInf, 0, sizeof startInf );
startInf.cb = sizeof(startInf);
// If you want to redirect result of command, set startInf.hStdOutput to a file
// or pipe handle that you can read it, otherwise we are done!
PROCESS_INFORMATION procInf;
memset( &procInf, 0, sizeof procInf );
BOOL b = CreateProcessW( NULL, cmdline, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &startInf, &procInf );
DWORD dwErr = 0;
if( b ) {
// Wait till cmd do its job
WaitForSingleObject( procInf.hProcess, INFINITE );
// Check whether our command succeeded?
GetExitCodeProcess( procInfo.hProcess, &dwErr );
// Avoid memory leak by closing process handle
CloseHandle( procInfo.hProcess );
} else {
dwErr = GetLastError();
}
if( dwErr ) {
// deal with error here
}