如何使用CreateProcess在cmd中执行命令

How to execute a command in cmd using CreateProcess?

本文关键字:执行 命令 cmd 何使用 CreateProcess      更新时间:2023-10-16

我正试图通过我的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);
}