简体   繁体   English

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

[英]cmd.exe immediately closes after calling with CreateProcess

I am trying to execute a batch file using CreateProcess function, but the cmd.exe immediately closes without opening the executing the batch file. 我正在尝试使用CreateProcess函数执行批处理文件,但是cmd.exe立即关闭而不打开执行批处理文件。

An argument (path of a directory) is also passed. 还传递一个参数(目录的路径)。

The c++ code is : 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;
}

And the Batch file is 批处理文件是

echo hello.

set directory=%~1

cd %directory%

dir > files.txt

pause

exit 0

The Output 输出

yay......

is got but the file files.txt nor the output of echo hello. 得到但文件files.txt或echo hello.的输出echo hello. is got. 得到了。

The answer it seemed was the need to enclose the whole command line (except \\c) with quotes. 答案似乎是需要用引号将整个命令行(\\ c除外)括起来。

hence the program becomes : 因此程序变为:

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;
}

EDIT : for the final code I changed /k back to /c 编辑 :对于最终代码,我将/ k更改为/ c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM