c++ - cmd.exe 在调用 CreateProcess 后立即关闭

标签 c++ batch-file cmd createprocess

我正在尝试使用 CreateProcess 函数执行批处理文件,但 cmd.exe 立即关闭而没有打开执行批处理文件。

还传递了一个参数(目录路径)。

C++代码是:

int main()
{
    std::wstring cmdPath;
    std::wstring batchFile;
    batchFile = L"\"B:\\code\\Batch\\all_files.bat\"";
    std::wstring args = L"\"B:\\code\\Batch\"";

    {
        wchar_t cmdP[500] = L"  ";
        GetEnvironmentVariable(L"COMSPEC", cmdP, 500);
        cmdPath = cmdP;
    }

    std::wstring CmdLine = L"/c " + batchFile + L" " + args;

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    if (!
        CreateProcess
        (
            cmdPath.c_str(),
            const_cast<LPWSTR>(CmdLine.c_str()),
            NULL, NULL, FALSE,
            CREATE_NEW_CONSOLE,
            NULL, NULL,
            &si,
            &pi
        )
        )
    {
        std::cout << "bad";
        std::cin.get();
        return 1;
    }
    std::cout << "yay......\n";
    std::cin.get();
    return 0;
}

批处理文件是

echo hello.

set directory=%~1

cd %directory%

dir > files.txt

pause

exit 0

输出

yay......

得到了,但是得到了文件 files.txt 和 echo hello. 的输出。

最佳答案

答案似乎是需要用引号将整个命令行(\c 除外)括起来。

因此程序变成:

int main()
{
    std::wstring cmdPath;
    std::wstring batchFile;
    batchFile = L"\"B:\\Harith Source code\\Batch\\all_files.bat\"";
    std::wstring args = L"\"B:\\Harith Source code\\Batch\"";

    {
        wchar_t cmdP[500] = L"  ";
        GetEnvironmentVariable(L"COMSPEC", cmdP, 500);
        cmdPath = cmdP;
    }

    std::wstring CmdLine = L"/c " + std::wstring(L"\"") + batchFile + L" " + args + L"\"";

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    if (!
        CreateProcess
        (
            cmdPath.c_str(),
            const_cast<LPWSTR>(CmdLine.c_str()),
            NULL, NULL, FALSE,
            CREATE_NEW_CONSOLE,
            NULL, NULL,
            &si,
            &pi
        )
        )
    {
        std::cout << "bad";
        std::cin.get();
        return 1;
    }
    std::cout << "yay......\n";
    std::cin.get();
    return 0;
}

编辑:对于最终代码,我将/k 改回/c

关于c++ - cmd.exe 在调用 CreateProcess 后立即关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964676/

相关文章:

java - 如何使用命令行检查Java类的异常终止

javascript - 使用javascript以管理员身份运行批处理的简单方法

java - 命令提示符中不存在包

c++ - dylib 中缺少符号

c++ - boost::asio::deadline_timer 不调用处理程序

c++ - 如何使用英特尔PIN捕获到阵列的所有负载?

c++ - 在模板 vector 上返回迭代器

batch-file - 在 Windows 中解压 tar.gz

batch-file - 启动通过批处理最小化的程序

windows - 使用大括号或循环时 sed 出现额外字符错误