Skip to content

armgit / WSM

Public Imported from GitHub
0

Run macOS applications on your Windows desktop, with a background runtime and integrated app windows.

C++
2.4 KB
Raw Blame
#include "wsm/child_processes.hpp"
#include <iostream>
#include <string>

int main(int argc, char**) {
    if (argc > 1) { Sleep(INFINITE); return 0; }
    wchar_t path[32768]{}; GetModuleFileNameW(nullptr, path, 32768);
    const std::wstring child_line = L"\"" + std::wstring(path) + L"\" --child";
    STARTUPINFOW outside_start{}; outside_start.cb = sizeof(outside_start);
    PROCESS_INFORMATION outside{};
    std::wstring outside_line = child_line;
    if (!CreateProcessW(nullptr, outside_line.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
                        nullptr, nullptr, &outside_start, &outside)) return 1;
    const auto cleanup_outside = [&] {
        TerminateProcess(outside.hProcess, 0); WaitForSingleObject(outside.hProcess, 3000);
        CloseHandle(outside.hProcess); CloseHandle(outside.hThread);
    };
    if (!wsm::runtime::initialize_child_processes()) { cleanup_outside(); return 2; }
    const auto bytes = WideCharToMultiByte(CP_ACP, 0, child_line.c_str(), -1, nullptr, 0, nullptr, nullptr);
    std::string owned_line(static_cast<size_t>(bytes), '\0');
    WideCharToMultiByte(CP_ACP, 0, child_line.c_str(), -1, owned_line.data(), bytes, nullptr, nullptr);
    STARTUPINFOA startup{}; startup.cb = sizeof(startup);
    PROCESS_INFORMATION owned{};
    if (!wsm::runtime::create_owned_process_a(nullptr, owned_line.data(), nullptr, nullptr, FALSE,
        CREATE_NO_WINDOW, nullptr, nullptr, &startup, &owned)) { cleanup_outside(); return 3; }
    BOOL in_job = FALSE;
    const bool supervised = IsProcessInJob(owned.hProcess, wsm::runtime::children_job, &in_job) && in_job;
    wsm::runtime::stop_child_processes();
    const bool stopped = WaitForSingleObject(owned.hProcess, 5000) == WAIT_OBJECT_0;
    const bool unrelated_alive = WaitForSingleObject(outside.hProcess, 0) == WAIT_TIMEOUT;
    PROCESS_INFORMATION rejected{};
    const bool relaunch_blocked = !wsm::runtime::create_owned_process_a(nullptr, owned_line.data(), nullptr,
        nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &startup, &rejected);
    if (!relaunch_blocked) { TerminateProcess(rejected.hProcess, 1); CloseHandle(rejected.hProcess); CloseHandle(rejected.hThread); }
    CloseHandle(owned.hProcess); CloseHandle(owned.hThread); cleanup_outside();
    if (!supervised || !stopped || !unrelated_alive || !relaunch_blocked) return 4;
    std::cout << "Owned children stop, unrelated processes survive, relaunch is blocked.\n";
    return 0;
}