gpt4 book ai didi

c++ - 如何使用 CreateProcess 在 cmd 中执行命令?

转载 作者:行者123 更新时间:2023-12-02 10:25:14 25 4
gpt4 key购买 nike

我正在尝试通过我的 c++ 程序启动命令行,然后让 cmd 运行命令。我不确定我做错了什么。我查看了 MSDN 文档,但无法理解代码中要更改的内容。

以下是我编写的代码块。我正在尝试启动 cmd,然后在 cmdArgs 中运行该命令。但是,在运行程序时,它只是启动 cmd 而不运行它的 nslookup 部分。我尝试过使用其他命令以及 ipconfig,但它们没有被执行。有人可以帮我理解我做错了什么。

当我启动程序时,它只是打开了 cmd。我要做的是让 cmdArgs 运行并在 cmd 屏幕上查看输出。

我是 C++ 新手,所以如果这是微不足道的,我深表歉意。我查看了网站上的其他问题,但似乎 cmdArgs 的格式是正确的 - 程序名称后跟 arg。

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:\Users\xxx>start /w cmd ipconfig

C:\Users\xxx>cmd ipconfig
Microsoft Windows [version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Tous droits réservés.

C:\Users\xxx>exit

C:\Users\xxx>

所以 cmd.exe ipconfig刚推了一个新的 cmd.exe不执行剩余的行。然后它等待来自其标准输入的命令。

您必须使用 cmd.exe /c ipconfig求新 cmd.exe执行命令,或 cmd.exe /K ipconfig如果您希望 cmd 在第一个命令后不退出:

C:\Users\serge.ballesta>cmd /c ipconfig

Configuration IP de Windows
...

所以你应该在你的代码中写:
...
LPTSTR cmdArgs = _T("C:\\Windows\\System32\\cmd.exe /k nslookup myip.opendns.com. resolver1.opendns.com");
...

关于c++ - 如何使用 CreateProcess 在 cmd 中执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39702655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com