使用CreateProcess调用后,cmd.exe立即关闭

时间:2018-02-24 15:55:33

标签: 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.的输出已获得。

1 个答案:

答案 0 :(得分:0)

答案似乎是需要用引号括起整个命令行(除了\ 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