簡體   English   中英

使用CreateProcess調用后,cmd.exe立即關閉

[英]cmd.exe immediately closes after calling with 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.的輸出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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM