static OwnedHandle startAgentProcess()

in src/libwinpty/winpty.cc [472:521]


static OwnedHandle startAgentProcess(
        const std::wstring &desktop,
        const std::wstring &controlPipeName,
        const std::wstring &params,
        DWORD creationFlags,
        DWORD &agentPid) {
    const std::wstring exePath = findAgentProgram();
    const std::wstring cmdline =
        (WStringBuilder(256)
            << L"\"" << exePath << L"\" "
            << controlPipeName << L' '
            << params).str_moved();

    auto cmdlineV = vectorWithNulFromString(cmdline);
    auto desktopV = vectorWithNulFromString(desktop);

    // Start the agent.
    STARTUPINFOW sui = {};
    sui.cb = sizeof(sui);
    sui.lpDesktop = desktop.empty() ? nullptr : desktopV.data();

    if (shouldSpecifyHideFlag()) {
        sui.dwFlags |= STARTF_USESHOWWINDOW;
        sui.wShowWindow = SW_HIDE;
    }
    PROCESS_INFORMATION pi = {};
    const BOOL success =
        CreateProcessW(exePath.c_str(),
                       cmdlineV.data(),
                       nullptr, nullptr,
                       /*bInheritHandles=*/FALSE,
                       /*dwCreationFlags=*/creationFlags,
                       nullptr, nullptr,
                       &sui, &pi);
    if (!success) {
        const DWORD lastError = GetLastError();
        const auto errStr =
            (WStringBuilder(256)
                << L"winpty-agent CreateProcess failed: cmdline='" << cmdline
                << L"' err=0x" << whexOfInt(lastError)).str_moved();
        throw LibWinptyException(
            WINPTY_ERROR_AGENT_CREATION_FAILED, errStr.c_str());
    }
    CloseHandle(pi.hThread);
    TRACE("Created agent successfully, pid=%u, cmdline=%s",
          static_cast<unsigned int>(pi.dwProcessId),
          utf8FromWide(cmdline).c_str());
    agentPid = pi.dwProcessId;
    return OwnedHandle(pi.hProcess);
}