我想执行一个简单的命令行但不显示窗口。因此,据我所知,我不能使用 System 并且必须使用 CreateProcess 。 例如,我有以下代码:
//.../
CreateProcess(NULL,input,NULL,NULL,false,NORMAL_PRIORITY_CLASS |
CREATE_NO_WINDOW,NULL,NULL,&startInf,&procInf);//)
//.../
如果输入是类似"ping www.google.com -n 2" 的行,它似乎可以工作。 不过,我需要的是删除功能。 因此我尝试了很多变体,例如:
input = "rd /S /Q \"D:\\ALEX_DATEN\\PC\\C++\\bla\"";
和
input = "rd /S /Q \"D:/DATEN/PC/C++/bla\"";
但是没有任何反应,函数返回失败:/ 如果我把它写成一个 .bat 文件(不使用“\”转义字符),删除就完美了!
有人知道我做错了什么吗?
附言不,我不是在编写破坏性病毒..如果那是我的目标,我肯定会找到更简单的方法...
最佳答案
某些系统命令,如 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
}
关于c++ - 如何使用 CreateProcess 执行简单的命令行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12921680/