如何使用CreateProcess在cmd中执行命令
How to execute a command in cmd using CreateProcess?
我正试图通过我的c++程序启动命令行,然后让cmd运行命令。我不确定我做错了什么。我已经看了MSDN文档,但我无法理解在我的代码中要改变什么。
下面是我写的代码块。我试图启动cmd,然后在cmdArgs中运行命令。然而,在运行程序时,它只是启动cmd而不运行它的nslookup部分。我也尝试过其他命令,比如ipconfig,但是它们都没有执行。有没有人能告诉我我做错了什么?
当我启动程序时,它只是打开cmd。我想做的是让cmdArgs运行并在cmd屏幕上查看输出。
我是c++的新手,所以如果这是微不足道的,我道歉。我在网站上看了其他问题,但似乎cmdArgs的格式是正确的-程序名称后面跟着参数。
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
LPTSTR cmdPath = _T("C:\Windows\System32\cmd.exe");
LPTSTR cmdArgs = _T("C:\Windows\System32\cmd.exe nslookup myip.opendns.com. resolver1.opendns.com");
if (!CreateProcess(cmdPath, cmdArgs, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
std::cout << "Create Process failed: " << GetLastError() << std::endl;
return "Failed";
}
您的程序完全按照您的要求去做:您只需启动cmd.exe可执行文件。只需在控制台窗口中进行测试:
C:Usersxxx>start /w cmd ipconfig
C:Usersxxx>cmd ipconfig
Microsoft Windows [version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Tous droits réservés.
C:Usersxxx>exit
C:Usersxxx>
所以cmd.exe ipconfig
只是推入了一个新的cmd.exe
而没有执行该行的剩余部分。然后等待来自标准输入的命令。
您必须使用cmd.exe /c ipconfig
来要求新的cmd.exe
执行命令,或cmd.exe /K ipconfig
,如果您希望cmd在第一个命令后不退出:
C:Usersserge.ballesta>cmd /c ipconfig
Configuration IP de Windows
...
所以你应该在你的代码中写:
...
LPTSTR cmdArgs = _T("C:\Windows\System32\cmd.exe /k nslookup myip.opendns.com. resolver1.opendns.com");
...
试试:
wchar_t command[] = L"nslookup myip.opendns.com. resolver1.opendns.com";
wchar_t cmd[MAX_PATH] ;
wchar_t cmdline[ MAX_PATH + 50 ];
swprintf_s( cmdline, L"%s /c %s", cmd, command );
STARTUPINFOW startInf;
memset( &startInf, 0, sizeof startInf );
startInf.cb = sizeof(startInf);
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 process completes
WaitForSingleObject( procInf.hProcess, INFINITE );
// Check process’s exit code
GetExitCodeProcess( procInf.hProcess, &dwErr );
// Avoid memory leak by closing process handle
CloseHandle( procInf.hProcess );
}
else
{
dwErr = GetLastError();
}
if( dwErr )
{
wprintf(_T(“Command failed. Error %dn”),dwErr);
}
相关文章:
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在 Minecraft 服务器上执行命令
- 如何在C++中执行命令并获取命令的返回代码标准输出和标准
- 如何查看完整的CMD执行命令,包括参数和标志?
- CPP 中 z3 的编译和执行命令?
- 线程保持运行并执行命令
- 在 MinGW 和 MinGW-64 上执行命令后变量为空?
- popen() 将执行命令的输出写入 cout
- 如何在 Heroku 中的 Python 服务器上执行 "g++" 命令?
- 以普通用户身份执行命令
- 如何在生成之前在 cmake 中执行命令?
- 如何使用 c++ 在 cmd 中使用管理员权限执行命令
- 如何在Unix Shell中的后台执行命令
- 如何从连接的控制台执行命令
- 尝试在路由器上执行命令。C++ & libssh
- 在服务器上执行命令,然后将结果发送到Windows中的客户端
- 通过C编程打开终端并执行命令
- 在远程服务器上执行命令行命令
- 在Linux上使用c++执行命令时被阻止
- 使用popen执行命令