Загрузка данных


#include <windows.h>
#include <iostream>

using namespace std;

const wchar_t* PIPE_NAME = L"\\\\.\\pipe\\PilgrimagePipe";

// ===================== СТРУКТУРЫ ОБМЕНА =====================
struct PilgrimRequest
{
    int id;
    int patienceMs;
};

struct ServerReply
{
    int status;      // 0 = FOOT, 1 = SHIP
    int shipId;
    int placeNumber;
};

void print_time()
{
    SYSTEMTIME lt;
    GetLocalTime(&lt);
    printf("%02d:%02d:%02d\t", lt.wHour, lt.wMinute, lt.wSecond);
}

int main(int argc, char* argv[])
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);

    int pilgrimId = 0;
    int patienceMs = 0;

    if (argc >= 3)
    {
        pilgrimId = atoi(argv[1]);
        patienceMs = atoi(argv[2]);
    }
    else
    {
        cout << "Введите id паломника: ";
        cin >> pilgrimId;

        cout << "Введите терпение в мс: ";
        cin >> patienceMs;
    }

    HANDLE hPipe;
    while (1)
    {
        hPipe = CreateFileW(
            PIPE_NAME,
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL
        );

        if (hPipe != INVALID_HANDLE_VALUE)
            break;

        if (GetLastError() != ERROR_PIPE_BUSY)
        {
            print_time();
            cout << "[ERROR] Could not open pipe. GLE=" << GetLastError() << '\n';
            return 1;
        }

        if (!WaitNamedPipeW(PIPE_NAME, 20000))
        {
            print_time();
            cout << "[ERROR] 20 second wait timed out.\n";
            return 1;
        }
    }

    print_time();
    cout << "[MESSAGE] Паломник #" << pilgrimId
         << " подключился к флоту через именованный канал.\n";

    PilgrimRequest request{};
    request.id = pilgrimId;
    request.patienceMs = patienceMs;

    DWORD cbIO = 0;
    BOOL fSuccess = WriteFile(
        hPipe,
        &request,
        sizeof(PilgrimRequest),
        &cbIO,
        NULL
    );

    if (!fSuccess || cbIO != sizeof(PilgrimRequest))
    {
        print_time();
        cout << "[ERROR] WriteFile failed. GLE=" << GetLastError() << '\n';
        CloseHandle(hPipe);
        return 1;
    }

    ServerReply reply{};
    fSuccess = ReadFile(
        hPipe,
        &reply,
        sizeof(ServerReply),
        &cbIO,
        NULL
    );

    if (!fSuccess || cbIO != sizeof(ServerReply))
    {
        print_time();
        cout << "[ERROR] ReadFile failed. GLE=" << GetLastError() << '\n';
        CloseHandle(hPipe);
        return 1;
    }

    if (reply.status == 0)
    {
        print_time();
        cout << "[MESSAGE] Паломник #" << pilgrimId
             << " не дождался корабля и пошел пешком.\n";
    }
    else
    {
        print_time();
        cout << "[MESSAGE] Паломник #" << pilgrimId
             << " сел на корабль #" << reply.shipId
             << ", место " << reply.placeNumber << ".\n";
    }

    CloseHandle(hPipe);
    return 0;
}