如何在 C++ 中使用 CreateProcessW 运行 具有多个参数的 exe

How to run an exe with multiple arguments with CreateProcessW in C++

我曾尝试在 C++ 中使用 this example 到 运行 使用 CreateProcessW() 的外部程序,但是,当我使用多个参数时,此代码似乎不起作用。

在我的例子中,我通过以下路径:

std::string pathToExe = "C:\Users\Aitor - ST\Documents\QtProjects\ErgoEvalPlatform\ErgonomicEvaluationPlatform\FACTS\xsim-runner.exe"

和以下参数:

std::string arguments = "--model=facts_input.xml --output_xml=something.xml"

这些参数在 cmd 中有效,但当我在 C++ 中使用它们时,它们似乎没有提供任何输出(xml 应该出现在同一文件夹中)。

有什么我可能遗漏的吗?

您必须在参数中传递完整的命令行,如下所示:

std::string arguments = "C:\Users\Aitor-ST\Documents\QtProjects\ErgoEvalPlatform\ErgonomicEvaluationPlatform\FACTS\xsim-runner.exe --model=facts_input.xml --output_xml=something.xml"

CreateProcessW 的第二个参数需要完整的命令行,而不仅仅是参数。它将这个传递给进程,如果目标进程是一个采用 agrs 的 C 程序,那么像往常一样,第一个参数将是模块名称,后面的其他参数将是 args。

希望对您有所帮助

我可以从您显示的代码中推断出两个潜在的问题。

Space 参数前

根据您将参数字符串连接到可执行字符串的方式,您可能会错过参数前的 space。没有代码,就无法分辨,但请尝试像这样更改参数字符串:

std::string arguments = " --model=facts_input.xml --output_xml=something.xml;"

当前目录

CreateProcess 产生一个从其父进程继承当前目录的子进程。您在参数中指定的 XML 文件使用相对路径。

尝试指定您在参数中传递的 XML 文件的完整路径,如下所示:

std::string arguments = " --model=\"C:\Users\Aitor - ST\Documents\QtProjects\ErgoEvalPlatform\ErgonomicEvaluationPlatform\FACTS\facts_input.xml\" --output_xml=\"C:\Users\Aitor - ST\Documents\QtProjects\ErgoEvalPlatform\ErgonomicEvaluationPlatform\FACTS\something.xml\"";

下面是显示"How to run an exe with multiple arguments with CreateProcessW in C++"的例子。你可以检查它是否有帮助。

启动器应用程序(控制台应用程序):

#include <iostream>
#include <windows.h>

int main()
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi; // The function returns this
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    CONST wchar_t* commandLine = TEXT("arg1 arg2 arg3");

    // Start the child process.
    if (!CreateProcessW(
        L"D:\Win32-Cases\TestTargetApp\Debug\TestTargetApp.exe",      // app path
        (LPWSTR)commandLine,     // Command line 
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi)           // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        throw std::exception("Could not create child process");
    }
    else
    {
        std::cout << "[          ] Successfully launched child process" << std::endl;
    }
}

将启动的目标应用程序(另一个控制台应用程序):

#include <iostream>
#include <windows.h>

int main(int argc, char *argv[])
{
    if (argc > 0)
    {
        for (int index = 0; index < argc; index++)
        {
            std::cout << argv[index] << std::endl;
        }
    }

    return 1;
}