Thursday, November 19, 2026
HomeC ProgrammingShopper, Threaded and Overlapped Servers

Shopper, Threaded and Overlapped Servers


Two applications on the identical Home windows machine want to speak. A file is clumsy and a TCP port is greater than the job wants. A named pipe suits: the server creates a pipe with a reputation equivalent to .pipemycplus-demo, and any native course of can open that identify, write a request and skim the reply. Home windows providers, database engines and construct instruments use them on a regular basis.

This information builds a named pipe shopper and three servers in trendy C++: a easy server that handles one shopper at a time, a multithreaded server with a std::thread per shopper and a single-threaded server that makes use of overlapped I/O to serve a number of shoppers directly. All 4 use RAII for handles, wide-character API calls, message-mode pipes and actual error reporting. A check program begins the servers and shoppers collectively and checks each transcript. The code was constructed with MSVC on Home windows 11 (C++17 and C++20, warnings as errors), the place all seven shopper/server assessments handed, and cross-compiled with MinGW-w64 on Linux.

The Quick Reply

What’s a named pipe in Home windows? A named, two-way channel between a server course of and its shoppers, opened by the file API. The server calls CreateNamedPipeW; a shopper opens the identical identify with CreateFileW; each then use ReadFile and WriteFile.

Which server design ought to I exploit? Begin with one thread per shopper: it’s the best to learn and works nicely for dozens of shoppers. Use overlapped I/O when one thread should serve many purchasers, or when the server already runs an occasion loop.

Named pipes or sockets? Named pipes for native, Home windows-only communication with Home windows entry management. TCP sockets when the opposite aspect could also be on one other machine or one other working system.

What Is a Named Pipe?

A named pipe is an inter-process communication (IPC) channel {that a} server creates below a reputation within the .pipe namespace. Purchasers connect with it by identify, and every connection will get its personal pipe occasion, so a server with 4 situations can discuss to 4 shoppers directly. Knowledge can movement as a byte stream or as separate messages.

Three concepts cowl many of the API:

  • The identify. A pipe’s full identify is ServerNamepipePipeName, the place ServerName is a interval for the native pc. Names usually are not case-sensitive and might be as much as 256 characters lengthy. The examples right here prefix each identify with mycplus- so they can not collide with one other program’s pipes.
  • Cases. Each name to CreateNamedPipeW with the identical identify creates yet one more occasion, and every occasion serves one shopper at a time. The server decides what number of situations might exist; when all of them are busy, a brand new shopper will get ERROR_PIPE_BUSY and has to attend.
  • Byte mode or message mode. In byte mode, a pipe behaves like a TCP stream: three writes of 10 bytes might arrive as one learn of 30. In message mode, each WriteFile is one message and the reader can get it again entire. All 4 applications right here use message mode, as a result of a request/reply protocol wants message boundaries.

Microsoft’s Named Pipes documentation covers the complete API, together with pipes reached over the community.

Named Pipes vs Sockets

Named pipes usually are not the one means for 2 processes to speak. This desk compares them with the 2 socket sorts you’re more than likely to contemplate as an alternative.

Characteristic Named pipe TCP socket on localhost Unix area socket
Working methods Home windows (Linux has FIFOs, a unique API) All Linux, macOS; Home windows 10 1803 and later
Handle .pipename IP deal with and port Path within the file system
Message boundaries Sure, in message mode No, a byte stream Sure, with SOCK_DGRAM or SOCK_SEQPACKET
Entry management Home windows safety descriptor on the pipe Firewall guidelines; any native person can join File permissions on the socket path
Distant shoppers Attainable over SMB; might be rejected Sure No
API CreateNamedPipeW, ConnectNamedPipe, ReadFile, WriteFile Winsock or BSD sockets BSD sockets

If the opposite finish might run on one other machine, the TCP shopper and server in C article builds the identical type of echo protocol over sockets, and UDP sender and receiver in C exhibits what adjustments when messages could also be misplaced.

Three Methods to Serve Purchasers

The shopper is similar for each server. What adjustments is how a server waits for its shoppers:

3 ways to serve named pipe shoppers pipe_server One occasion, one thread thread_server One thread per shopper overlapped_server One thread, overlapped I/O fundamental thread occasion 1 shopper A shopper B waits ERROR_PIPE_BUSY till A disconnects fundamental thread ConnectNamedPipe, then hand the occasion over occasion 1 std::thread shopper A occasion 2 std::thread shopper B occasion 3 std::thread shopper C blocking calls, one stack per shopper fundamental thread WaitForMultipleObjects occasion 0 OVERLAPPED+occasion shopper A occasion 1 OVERLAPPED+occasion shopper B occasion 2 OVERLAPPED+occasion shopper C occasion 3 OVERLAPPED+occasion listening All three use the identical shopper and the identical messages. They differ in how the server waits. Easiest first; threads for just a few shoppers; overlapped I/O for a lot of shoppers on one thread.
Determine 1: The straightforward server makes the second shopper wait. The thread server provides each shopper its personal thread, and the overlapped server serves each shopper from one thread.
  • One occasion, one thread (pipe_server). The best attainable server: it waits for a shopper, serves it till it leaves, then waits for the subsequent. A second shopper has to attend.
  • One thread per shopper (thread_server). The principle thread accepts connections and fingers every one to a brand new std::thread. Each name is obstructing, which retains the code brief.
  • One thread, overlapped I/O (overlapped_server). A set variety of situations, every with its personal OVERLAPPED construction and occasion. One thread begins each operation with out ready for it, then waits for whichever finishes first.

Each server solutions every message with ECHO and the message in capitals, so a check can inform which reply belongs to which request.

The Shared Helpers

All 4 applications embrace one header. It holds 4 small items that each named pipe program wants and that the Win32 API doesn’t present:

  • UniqueHandle, a move-only proprietor for a HANDLE, in the identical spirit as std::unique_ptr (see sensible pointers in C++). Each deal with is closed precisely as soon as, on each path, together with early returns. The C++ reminiscence administration information explains the RAII concept behind it.
  • error_text, which turns an error code into error 231 (ERROR_PIPE_BUSY). It prints the symbolic identify as an alternative of the FormatMessage textual content, as a result of that textual content is translated on non-English Home windows and would make check output depend upon the language.
  • read_message and write_message, which ship and obtain one entire message. read_message handles the case the place a message is longer than its 512-byte buffer (see “Messages Longer Than the Buffer” beneath).
  • pipe_path, which builds the complete wide-character pipe identify.
// pipe_common.h - small helpers shared by the named pipe examples:
// a RAII wrapper for Home windows handles, readable error messages, and the
// conversion from a brief pipe identify to the complete .pipe path.
#pragma as soon as

#ifndef WIN32_LEAN_AND_MEAN
#outline WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#outline NOMINMAX
#endif
#embrace <home windows.h>

#embrace <string>
#embrace <utility>

// Owns one HANDLE and closes it precisely as soon as. Transfer-only, like std::unique_ptr.
class UniqueHandle {
public:
    UniqueHandle() = default;
    express UniqueHandle(HANDLE h) : h_(h) {}
    ~UniqueHandle() { reset(); }
    UniqueHandle(const UniqueHandle&) = delete;
    UniqueHandle& operator=(const UniqueHandle&) = delete;
    UniqueHandle(UniqueHandle&& different) noexcept : h_(std::alternate(different.h_, INVALID_HANDLE_VALUE)) {}
    UniqueHandle& operator=(UniqueHandle&& different) noexcept
    {
        if (this != &different) {
            reset();
            h_ = std::alternate(different.h_, INVALID_HANDLE_VALUE);
        }
        return *this;
    }

    HANDLE get() const { return h_; }
    bool legitimate() const { return h_ != INVALID_HANDLE_VALUE && h_ != nullptr; }
    void reset()
    {
        if (legitimate())
            CloseHandle(h_);
        h_ = INVALID_HANDLE_VALUE;
    }

non-public:
    HANDLE h_ = INVALID_HANDLE_VALUE;
};

// "error 5 (ERROR_ACCESS_DENIED)". The symbolic names are printed as an alternative of
// FormatMessage textual content, as a result of that textual content is translated on non-English Home windows.
inline std::string error_text(DWORD code)
{
    const char* identify = nullptr;
    swap (code) {
    case ERROR_FILE_NOT_FOUND:     identify = "ERROR_FILE_NOT_FOUND"; break;
    case ERROR_ACCESS_DENIED:      identify = "ERROR_ACCESS_DENIED"; break;
    case ERROR_BROKEN_PIPE:        identify = "ERROR_BROKEN_PIPE"; break;
    case ERROR_PIPE_BUSY:          identify = "ERROR_PIPE_BUSY"; break;
    case ERROR_NO_DATA:            identify = "ERROR_NO_DATA"; break;
    case ERROR_PIPE_CONNECTED:     identify = "ERROR_PIPE_CONNECTED"; break;
    case ERROR_MORE_DATA:          identify = "ERROR_MORE_DATA"; break;
    case ERROR_SEM_TIMEOUT:        identify = "ERROR_SEM_TIMEOUT"; break;
    case ERROR_IO_PENDING:         identify = "ERROR_IO_PENDING"; break;
    default: break;
    }
    std::string textual content = "error " + std::to_string(code);
    if (identify != nullptr)
        textual content += std::string(" (") + identify + ")";
    return textual content;
}

// "demo" turns into L".pipemycplus-demo". The prefix retains the examples'
// pipes aside from different applications' pipes on the identical machine.
inline std::wstring pipe_path(const std::string& identify)
{
    std::wstring path = L"\.pipemycplus-";
    for (char c : identify)
        path += static_cast<wchar_t>(static_cast<unsigned char>(c));
    return path;
}

// Reads one entire message from a message-mode pipe. Returns false when the
// different finish has closed the pipe (or on some other error, saved in *error).
inline bool read_message(HANDLE pipe, std::string& message, DWORD* error)
{
    message.clear();
    char buffer[512];
    for (;;) {
        DWORD received = 0;
        if (ReadFile(pipe, buffer, static_cast<DWORD>(sizeof buffer), &received, nullptr)) {
            message.append(buffer, received);
            return true;                       // the message is full
        }
        const DWORD e = GetLastError();
        if (e == ERROR_MORE_DATA) {            // the message is longer than the buffer
            message.append(buffer, received);
            proceed;
        }
        *error = e;
        return false;
    }
}

inline bool write_message(HANDLE pipe, const std::string& message, DWORD* error)
{
    DWORD written = 0;
    if (!WriteFile(pipe, message.knowledge(), static_cast<DWORD>(message.measurement()), &written, nullptr)
        || written != message.measurement()) {
        *error = GetLastError();
        return false;
    }
    return true;
}

// The reply each server sends: the request in capitals, so a check can inform
// which reply belongs to which request.
inline std::string make_reply(const std::string& request)
{
    std::string reply = "ECHO ";
    for (char c : request)
        reply += (c >= 'a' && c <= 'z') ? static_cast<char>(c - 'a' + 'A') : c;
    return reply;
}

A Easy Named Pipe Server

A named pipe server wants 5 steps:

  1. Create a pipe occasion with CreateNamedPipeW.
  2. Await a shopper with ConnectNamedPipe.
  3. Learn requests and write replies with ReadFile and WriteFile.
  4. Disconnect the shopper with DisconnectNamedPipe, which makes the occasion prepared for the subsequent shopper.
  5. Shut the occasion deal with (right here, UniqueHandle does it).
// pipe_server.cpp - the best named pipe server. It creates one pipe
// occasion, serves one shopper at a time, and solutions each message.
//
// utilization: pipe_server [name] [clients]    defaults: demo 1
#embrace "pipe_common.h"

#embrace <cstdlib>
#embrace <iostream>
#embrace <string>

int fundamental(int argc, char** argv)
{
    const std::string identify = argc > 1 ? argv[1] : "demo";
    const int shoppers = argc > 2 ? std::atoi(argv[2]) : 1;
    const std::wstring path = pipe_path(identify);

    // FILE_FLAG_FIRST_PIPE_INSTANCE: fail if one other course of already owns this
    // pipe identify, so no different program can pose as this server.
    // PIPE_REJECT_REMOTE_CLIENTS: settle for shoppers on this pc solely.
    UniqueHandle pipe(CreateNamedPipeW(
        path.c_str(),
        PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
        1,          // one occasion: one shopper at a time
        4096, 4096, // output and enter buffer sizes (advisory)
        0,          // default timeout for WaitNamedPipe
        nullptr));  // default safety: see "Safety: Who Can Join"
    if (!pipe.legitimate()) {
        std::cout << "server: CreateNamedPipe failed: " << error_text(GetLastError()) << 'n';
        return 1;
    }
    std::cout << "server: listening on pipe mycplus-" << identify << std::endl;

    for (int served = 0; served < shoppers; ++served) {
        // Await a shopper. If one linked between CreateNamedPipe and this
        // name, ConnectNamedPipe fails with ERROR_PIPE_CONNECTED: that's success.
        if (!ConnectNamedPipe(pipe.get(), nullptr) && GetLastError() != ERROR_PIPE_CONNECTED) {
            std::cout << "server: ConnectNamedPipe failed: " << error_text(GetLastError()) << 'n';
            return 1;
        }
        std::cout << "server: shopper connectedn";

        std::string request;
        DWORD error = 0;
        whereas (read_message(pipe.get(), request, &error)) {
            std::cout << "server: obtained "" << request << ""n";
            if (!write_message(pipe.get(), make_reply(request), &error))
                break;
        }
        if (error != ERROR_BROKEN_PIPE)            // anything is an actual failure
            std::cout << "server: learn failed: " << error_text(error) << 'n';

        FlushFileBuffers(pipe.get());              // let the shopper learn the final reply
        DisconnectNamedPipe(pipe.get());           // prepared for the subsequent shopper
        std::cout << "server: shopper disconnectedn";
    }
    return 0;
}

Three particulars are straightforward to get incorrect:

  • ERROR_PIPE_CONNECTED is success. If a shopper connects within the brief hole between CreateNamedPipeW and ConnectNamedPipe, the decision returns FALSE with this code. A server that treats each FALSE as an error drops that shopper.
  • ERROR_BROKEN_PIPE is the conventional finish. When the shopper closes its deal with, the subsequent ReadFile fails with it. Solely different codes are value reporting.
  • FlushFileBuffers earlier than DisconnectNamedPipe. Disconnecting throws away any knowledge the shopper has not learn but. Flushing first waits till the shopper has learn the final reply.

The server takes the pipe identify and the variety of shoppers to function arguments. An actual server would loop without end; the rely lets the assessments cease it cleanly.

A Named Pipe Shopper

The shopper opens the pipe with CreateFileW, precisely as if it had been a file, then switches its deal with to message mode. That second step issues: Microsoft’s shopper documentation notes that the deal with CreateFile returns begins in byte-read mode, even when the server created a message-mode pipe.

// pipe_client.cpp - connects to a named pipe server, sends every argument as
// one message, and prints the reply.
//
// utilization: pipe_client [name] [message...]    defaults: demo "whats up"
#embrace "pipe_common.h"

#embrace <iostream>
#embrace <string>
#embrace <vector>

// Opens the pipe, ready for a free occasion. Provides up after about 5 seconds.
static UniqueHandle join(const std::wstring& path)
{
    for (int try = 0; try < 50; ++try) {
        UniqueHandle pipe(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr,
                                      OPEN_EXISTING, 0, nullptr));
        if (pipe.legitimate())
            return pipe;

        const DWORD error = GetLastError();
        if (error == ERROR_PIPE_BUSY)
            WaitNamedPipeW(path.c_str(), 100);    // each occasion is busy: await one
        else if (error == ERROR_FILE_NOT_FOUND)
            Sleep(100);                           // the server has not created the pipe but
        else {
            std::cout << "shopper: CreateFile failed: " << error_text(error) << 'n';
            return UniqueHandle();
        }
    }
    std::cout << "shopper: no server after 5 secondsn";
    return UniqueHandle();
}

int fundamental(int argc, char** argv)
{
    const std::string identify = argc > 1 ? argv[1] : "demo";
    std::vector<std::string> messages(argv + (argc > 2 ? 2 : argc), argv + argc);
    if (messages.empty())
        messages.push_back("whats up");

    UniqueHandle pipe = join(pipe_path(identify));
    if (!pipe.legitimate())
        return 1;

    // A shopper deal with begins in byte mode; swap it to message mode so every
    // ReadFile returns one entire reply.
    DWORD mode = PIPE_READMODE_MESSAGE;
    if (!SetNamedPipeHandleState(pipe.get(), &mode, nullptr, nullptr)) {
        std::cout << "shopper: SetNamedPipeHandleState failed: " << error_text(GetLastError()) << 'n';
        return 1;
    }

    for (const std::string& message : messages) {
        DWORD error = 0;
        std::string reply;
        if (!write_message(pipe.get(), message, &error) || !read_message(pipe.get(), reply, &error)) {
            std::cout << "shopper: switch failed: " << error_text(error) << 'n';
            return 1;
        }
        std::cout << "shopper: despatched "" << message << "", received "" << reply << ""n";
    }
    return 0;    // closing the deal with tells the server this shopper is completed
}

The join operate handles the 2 methods a connection try can fail on a wholesome system. ERROR_PIPE_BUSY means the pipe exists however each occasion is serving a shopper, so the shopper calls WaitNamedPipeW and tries once more. ERROR_FILE_NOT_FOUND means no server has created the pipe but. Both means, the shopper provides up after about 5 seconds as an alternative of hanging without end.

Operating the Shopper and Server

Construct with CMake (see “Supply Code and Checks” beneath), then begin the server in a single terminal, asking it to serve two shoppers:

> pipe_server demo 2
server: listening on pipe mycplus-demo

Run two shoppers from a second terminal:

> pipe_client demo whats up "named pipes"
shopper: despatched "whats up", received "ECHO HELLO"
shopper: despatched "named pipes", received "ECHO NAMED PIPES"
> pipe_client demo "second shopper"
shopper: despatched "second shopper", received "ECHO SECOND CLIENT"

The server’s terminal now exhibits each conversations, and the server exits after the second shopper leaves:

server: listening on pipe mycplus-demo
server: shopper linked
server: obtained "whats up"
server: obtained "named pipes"
server: shopper disconnected
server: shopper linked
server: obtained "second shopper"
server: shopper disconnected

These are the traces the easy check checks on each construct.

A Multithreaded Named Pipe Server

To serve a number of shoppers directly, a server wants a number of situations. The thread server creates a brand new occasion for each shopper and passes it to a std::thread, which owns it till the shopper leaves:

// thread_server.cpp - a multithreaded named pipe server. The principle thread
// waits for shoppers; every linked shopper will get its personal std::thread.
//
// utilization: thread_server [name] [clients]    defaults: demo 3
#embrace "pipe_common.h"

#embrace <cstdlib>
#embrace <iostream>
#embrace <mutex>
#embrace <sstream>
#embrace <string>
#embrace <thread>
#embrace <vector>

static std::mutex print_mutex;    // one line at a time on std::cout

static void say(const std::string& line)
{
    std::lock_guard<std::mutex> lock(print_mutex);
    std::cout << line << std::endl;
}

// Runs by itself thread and owns its pipe occasion till the shopper leaves.
static void serve(UniqueHandle pipe, int id)
{
    std::string request;
    DWORD error = 0;
    whereas (read_message(pipe.get(), request, &error)) {
        say("server: shopper " + std::to_string(id) + " despatched "" + request + """);
        if (!write_message(pipe.get(), make_reply(request), &error))
            break;
    }
    if (error != ERROR_BROKEN_PIPE)
        say("server: shopper " + std::to_string(id) + " failed: " + error_text(error));
    FlushFileBuffers(pipe.get());
    DisconnectNamedPipe(pipe.get());
    say("server: shopper " + std::to_string(id) + " disconnected");
}   // the UniqueHandle closes this occasion right here

int fundamental(int argc, char** argv)
{
    const std::string identify = argc > 1 ? argv[1] : "demo";
    const int shoppers = argc > 2 ? std::atoi(argv[2]) : 3;
    const std::wstring path = pipe_path(identify);

    std::vector<std::thread> staff;
    int consequence = 0;
    for (int id = 1; id <= shoppers; ++id) {
        // A brand new occasion for each shopper. Solely the primary might declare the identify.
        const DWORD open_mode = PIPE_ACCESS_DUPLEX | (id == 1 ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0);
        UniqueHandle pipe(CreateNamedPipeW(
            path.c_str(), open_mode,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
            PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, nullptr));
        if (!pipe.legitimate()) {
            say("server: CreateNamedPipe failed: " + error_text(GetLastError()));
            consequence = 1;
            break;
        }
        if (id == 1)
            say("server: listening on pipe mycplus-" + identify);

        if (!ConnectNamedPipe(pipe.get(), nullptr) && GetLastError() != ERROR_PIPE_CONNECTED) {
            say("server: ConnectNamedPipe failed: " + error_text(GetLastError()));
            consequence = 1;
            break;
        }
        say("server: shopper " + std::to_string(id) + " linked");
        staff.emplace_back(serve, std::transfer(pipe), id);
    }

    for (std::thread& employee : staff)
        employee.be part of();    // wait for each shopper to complete earlier than exiting
    return consequence;
}

The design follows immediately from the API:

  • Solely the primary occasion claims the identify. FILE_FLAG_FIRST_PIPE_INSTANCE is about as an example 1 solely. Later situations of the identical pipe should not use it, or they’d fail too.
  • Each occasion should move the identical nMaxInstances. CreateNamedPipeW requires it; right here each name passes PIPE_UNLIMITED_INSTANCES (255).
  • Possession strikes into the thread. std::transfer(pipe) fingers the UniqueHandle to serve, so every occasion is closed by the thread that used it, and the primary thread can not contact it by mistake.
  • std::cout wants a lock. A number of threads print directly. With out print_mutex, their traces would interleave.
  • The server joins its threads. Getting back from fundamental whereas staff are nonetheless operating would finish the method and lower their shoppers off mid-conversation. The assessments verify that each shopper finishes.

One thread per shopper prices a stack per connection (1 MB of reserved deal with house by default on Home windows), which is ok for tens or tons of of shoppers. For hundreds, the overlapped design scales higher.

An Overlapped I/O Named Pipe Server

Overlapped I/O lets one thread begin a learn, a write or a join, and return instantly. When the operation finishes, Home windows indicators the occasion in its OVERLAPPED construction. The server beneath retains 4 situations, every with its personal occasion and state, and waits on all 4 occasions with WaitForMultipleObjects:

// overlapped_server.cpp - one thread serves a number of shoppers directly with
// overlapped (asynchronous) I/O. Each pipe occasion has an OVERLAPPED
// construction with its personal occasion, and WaitForMultipleObjects studies which
// occasion completed an operation.
//
// utilization: overlapped_server [name] [clients]    defaults: demo 3
#embrace "pipe_common.h"

#embrace <cstdlib>
#embrace <iostream>
#embrace <string>
#embrace <vector>

namespace {

constexpr DWORD kInstances = 4;    // WaitForMultipleObjects permits as much as 64

enum class State { Connecting, Studying, Writing };

struct Occasion {
    UniqueHandle pipe;
    UniqueHandle occasion;
    OVERLAPPED overlapped{};
    State state = State::Connecting;
    char buffer[512];
    std::string request;
    std::string reply;
    int shopper = 0;              // 0 whereas no shopper is linked
    bool connect_pending = false;  // false: the shopper arrived earlier than ConnectNamedPipe
};

// Begins an asynchronous join. Returns false on an actual error.
bool start_connect(Occasion& in)
{
    in.state = State::Connecting;
    if (ConnectNamedPipe(in.pipe.get(), &in.overlapped))
        return false;    // overlapped ConnectNamedPipe ought to by no means return TRUE
    swap (GetLastError()) {
    case ERROR_IO_PENDING:
        in.connect_pending = true;     // the occasion is signaled when a shopper arrives
        return true;
    case ERROR_PIPE_CONNECTED:
        in.connect_pending = false;    // a shopper arrived already: no I/O to attend for,
        SetEvent(in.occasion.get());      // so sign the occasion by hand
        return true;
    case ERROR_NO_DATA:
        DisconnectNamedPipe(in.pipe.get());    // a shopper got here and went: hear once more
        return start_connect(in);
    default:
        return false;
    }
}

// Begins an asynchronous learn or write. ERROR_IO_PENDING is the conventional case;
// a name that completed directly indicators the occasion too, so each are dealt with in
// the identical place: the primary loop.
bool start_io(Occasion& in)


}    // namespace

int fundamental(int argc, char** argv)
{
    const std::string identify = argc > 1 ? argv[1] : "demo";
    const int shoppers = argc > 2 ? std::atoi(argv[2]) : 3;
    const std::wstring path = pipe_path(identify);

    std::vector<Occasion> situations(kInstances);
    std::vector<HANDLE> occasions;
    for (DWORD i = 0; i < kInstances; ++i) {
        Occasion& in = situations[i];
        in.occasion = UniqueHandle(CreateEventW(nullptr, TRUE, FALSE, nullptr));    // guide reset
        in.overlapped.hEvent = in.occasion.get();
        in.pipe = UniqueHandle(CreateNamedPipeW(
            path.c_str(),
            PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | (i == 0 ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0),
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
            kInstances, 4096, 4096, 0, nullptr));
        if (!in.occasion.legitimate() || !in.pipe.legitimate() || !start_connect(in)) {
            std::cout << "server: establishing occasion " << i << " failed: "
                      << error_text(GetLastError()) << 'n';
            return 1;
        }
        occasions.push_back(in.occasion.get());
    }
    std::cout << "server: listening on pipe mycplus-" << identify << " with " << kInstances
              << " situations" << std::endl;

    int linked = 0;
    int completed = 0;
    whereas (completed < shoppers) {
        const DWORD signaled = WaitForMultipleObjects(static_cast<DWORD>(occasions.measurement()),
                                                      occasions.knowledge(), FALSE, INFINITE);
        const DWORD i = signaled - WAIT_OBJECT_0;
        if (i >= kInstances) {
            std::cout << "server: WaitForMultipleObjects failed: " << error_text(GetLastError()) << 'n';
            return 1;
        }
        Occasion& in = situations[i];

        DWORD bytes = 0;
        const bool no_io = in.state == State::Connecting && !in.connect_pending;
        const BOOL okay = no_io || GetOverlappedResult(in.pipe.get(), &in.overlapped, &bytes, FALSE);
        const DWORD error = okay ? static_cast<DWORD>(ERROR_SUCCESS) : GetLastError();
        ResetEvent(in.occasion.get());

        bool next_ok = true;
        if (in.state == State::Connecting) {
            if (!okay) {
                std::cout << "server: join failed: " << error_text(error) << 'n';
                return 1;
            }
            in.shopper = ++linked;
            std::cout << "server: shopper " << in.shopper << " linked on occasion " << i << 'n';
            in.request.clear();
            in.state = State::Studying;
            next_ok = start_io(in);
        } else if (in.state == State::Studying && (okay || error == ERROR_MORE_DATA)) {
            in.request.append(in.buffer, bytes);
            if (error == ERROR_MORE_DATA) {
                next_ok = start_io(in);              // learn the remainder of the message
            } else {
                std::cout << "server: shopper " << in.shopper << " despatched "" << in.request << ""n";
                in.reply = make_reply(in.request);
                in.state = State::Writing;
                next_ok = start_io(in);
            }
        } else if (in.state == State::Writing && okay && bytes == in.reply.measurement()) {
            in.request.clear();
            in.state = State::Studying;
            next_ok = start_io(in);
        } else {
            next_ok = false;    // the shopper closed its finish, or the switch failed
            if (error != ERROR_BROKEN_PIPE)
                std::cout << "server: shopper " << in.shopper << " failed: " << error_text(error) << 'n';
        }

        if (!next_ok) {
            if (in.state != State::Connecting && in.shopper != 0) {
                std::cout << "server: shopper " << in.shopper << " disconnectedn";
                ++completed;
            }
            in.shopper = 0;
            DisconnectNamedPipe(in.pipe.get());    // recycle the occasion for a brand new shopper
            if (completed < shoppers && !start_connect(in)) {
                std::cout << "server: reconnect failed: " << error_text(GetLastError()) << 'n';
                return 1;
            }
        }
    }
    // Cases nonetheless ready for a shopper have a ConnectNamedPipe pending that
    // makes use of their OVERLAPPED and occasion. Cancel it and await the cancellation
    // earlier than these objects are destroyed.
    for (Occasion& in : situations) {
        DWORD ignored = 0;
        if (CancelIoEx(in.pipe.get(), &in.overlapped))
            GetOverlappedResult(in.pipe.get(), &in.overlapped, &ignored, TRUE);
    }
    std::cout << "server: shoppers served: " << completed << std::endl;
    return 0;
}

Every occasion strikes by three states: Connecting, Studying and Writing. Each time its occasion fires, the loop checks the consequence with GetOverlappedResult, decides what the occasion ought to do subsequent and begins that operation. When a shopper leaves, the occasion is disconnected and goes again to Connecting, prepared for the subsequent shopper.

4 particulars make the distinction between a server that works and one which works solely in testing:

  • A join that’s already completed has no I/O to verify. If a shopper arrived earlier than ConnectNamedPipe, the decision returns ERROR_PIPE_CONNECTED, and the server units the occasion by hand. There isn’t any pending operation, so calling GetOverlappedResult on it could be incorrect. connect_pending data the distinction, as Microsoft’s overlapped server instance does with its fPendingIO flag.
  • One operation per occasion at a time. All three operations on an occasion share one occasion, so a accomplished occasion may belong to any of them if two had been in flight. The state machine begins the subsequent operation solely after the earlier one has completed.
  • Guide-reset occasions. The occasions are created manual-reset, and the loop resets every one after studying its consequence.
  • Pending I/O should finish earlier than its OVERLAPPED is destroyed. When the server finishes, situations which might be nonetheless listening have a ConnectNamedPipe in progress that refers to their OVERLAPPED and occasion. CancelIoEx cancels it, and GetOverlappedResult with TRUE waits for the cancellation, earlier than these objects exit of scope.

WaitForMultipleObjects can wait on at most 64 handles. Past that, the standard device is an I/O completion port, which lets a small pool of threads serve hundreds of situations.

Messages Longer Than the Buffer

A message-mode pipe retains message boundaries, however it doesn’t make each message suit your buffer. When a message is longer than the buffer handed to ReadFile, Home windows returns as a lot as suits, and ReadFile fails with ERROR_MORE_DATA. The remainder of the message continues to be within the pipe, ready for the subsequent learn.

read_message within the shared header handles this by appending every bit and studying once more till ReadFile succeeds. The overlapped server does the identical inside its Studying state. The long-simple and long-overlapped assessments ship a 1,500-byte message by 512-byte buffers to verify each paths, and the shopper’s reply should come again full.

The shopper’s swap to message mode issues right here too. A shopper deal with left in byte mode by no means sees ERROR_MORE_DATA: its first learn returns 512 bytes as successful, and the reply arrives lower brief.

Safety: Who Can Hook up with a Named Pipe

A named pipe is a securable object, and the defaults are extra open than most individuals anticipate. With a null safety descriptor, CreateNamedPipeW provides full management to the LocalSystem account, directors and the creator proprietor, and skim entry to the Everybody group and the nameless account. The examples add two flags on prime:

  • FILE_FLAG_FIRST_PIPE_INSTANCE makes CreateNamedPipeW fail with ERROR_ACCESS_DENIED if any occasion of the identify already exists. With out it, one other course of that creates the identical pipe identify first can sit in entrance of your server and obtain your shoppers’ requests. The duplicate-name check begins a second server on a reputation that’s in use and checks that it fails with precisely that error.
  • PIPE_REJECT_REMOTE_CLIENTS refuses connections from different computer systems. Pipes are reachable over the community by default, by the ServerNamepipe type of the identify.

A manufacturing server normally goes additional: it passes a SECURITY_ATTRIBUTES with a DACL that enables solely the customers or service accounts that want entry. A server also can be taught who the shopper is with GetNamedPipeClientProcessId, or act because the shopper with ImpersonateNamedPipeClient. Named Pipe Safety and Entry Rights lists the entry rights concerned.

Widespread Errors with Named Pipes

  • Treating ERROR_PIPE_CONNECTED as a failure. It means a shopper linked early. The connection is ok.
  • Studying a message-mode pipe by a byte-mode deal with. Shopper handles begin in byte mode. Name SetNamedPipeHandleState with PIPE_READMODE_MESSAGE.
  • Ignoring ERROR_MORE_DATA. Lengthy messages arrive in items. Preserve studying till ReadFile succeeds.
  • Calling DisconnectNamedPipe with out FlushFileBuffers. The shopper might lose the final reply.
  • Forgetting DisconnectNamedPipe earlier than reusing an occasion. ConnectNamedPipe on an occasion that also belongs to a departed shopper fails with ERROR_NO_DATA, and the subsequent shopper isn’t served. The easy check catches this.
  • Passing slim strings to the generic operate names. CreateNamedPipe("\.pipex", ...) compiles solely when UNICODE just isn’t outlined, and Visible Studio defines it for brand spanking new tasks. Name the W capabilities with L"..." strings, because the examples do.
  • Printing a DWORD with %d. DWORD is unsigned. Use %lu with printf, or std::cout.
  • Creating each occasion with FILE_FLAG_FIRST_PIPE_INSTANCE. Solely the primary occasion might use it; the second would fail with ERROR_ACCESS_DENIED.

Key Takeaways

  • A named pipe is an area, named, two-way channel between processes on Home windows, opened with the file API.
  • Every occasion serves one shopper. Extra situations imply extra simultaneous shoppers.
  • Use message mode for request/reply protocols, and keep in mind that shopper handles begin in byte mode.
  • ERROR_PIPE_CONNECTED means success, ERROR_BROKEN_PIPE means the opposite aspect closed and ERROR_MORE_DATA means preserve studying.
  • One thread per shopper is the best multi-client design; overlapped I/O serves many purchasers from one thread.
  • Declare the identify with FILE_FLAG_FIRST_PIPE_INSTANCE, and reject distant shoppers until you want them.

Conclusion

Named pipes give Home windows applications a quick, native channel with message boundaries and Home windows safety in-built. The API is small, however the particulars carry the load: which error codes imply success, which mode a deal with is in, when an overlapped operation is admittedly completed. Wrapping handles in RAII and studying entire messages in a single helper takes most of these particulars off the desk, and the three servers present how far the identical shopper can go, from one shopper at a time to many purchasers on one thread.

For extra C++ subjects, from the language fundamentals to methods programming, see the C++ part.

Supply Code and Checks

named-pipes workflow status

All applications on this web page are within the networking/named-pipes listing of the MYCPLUS C++ examples repository.

Construct and check (Home windows, in a Developer PowerShell or any shell with CMake and MSVC):

cmake -S . -B construct
cmake --build construct --config Launch
ctest --test-dir construct -C Launch --output-on-failure

What the construct checks.

  • Compilers: MSVC with /W4 /WX /permissive- in C++17 and C++20, and a MinGW-w64 cross-compile from Linux with -Wall -Wextra -pedantic -Werror -Wconversion.
  • Seven shopper/server eventualities. A check program begins the servers and shoppers as separate processes and compares the complete transcript with an anticipated file: two shoppers in flip, three shoppers directly on every multi-client server, a 1,500-byte message on the straightforward and overlapped servers, a second server making an attempt to take a reputation in use and a shopper with no server.
  • Concurrent runs. When three shoppers run directly, the order through which a server meets them varies, so these transcripts substitute the shopper and occasion numbers with # and type the server’s traces. Each message and each reply continues to be checked.

What I Verified

The Home windows column comes from run_all.ps1 within the repository, run on Home windows 11 (construct 26300) with MSVC. The Linux column was run for this text on Ubuntu 24.04 (x86-64, MinGW-w64 GCC 13).

Examine Ubuntu 24.04 Home windows 11
Construct with warnings as errors MinGW-w64 cross-compile, C++17 and C++20: all 5 applications handed MSVC /W4 /WX /permissive-, C++17 and C++20: handed
CTest: 7 shopper/server eventualities Not relevant (the applications run solely on Home windows) 7 of seven in C++17 and in C++20
Deliberate errors: 6 bugs {that a} check should catch Not relevant All 6 caught

Not lined: pipes between two computer systems (the servers reject distant shoppers), 32-bit builds and Home windows variations earlier than Home windows 10.

Previous articleOrbin' with Amp
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments