Overview / System & concurrency

process

Spawns and waits on child processes and provides local IPC: a framed message channel, shared memory, a zero-copy ring and named cross-process synchronization.

Always compiled: part of the core build.Include #include <ethereal/cpp/process/process_inc.hpp>C layer

process_inc.hpp

#include <ethereal/cpp/process/process_inc.hpp>

Aggregate entry point of the Process module.

Child processes and communication between processes on the same machine. Including this header brings the whole module.

  • Ethereal::Process::CProcess creates a child, writes to its input and reads its output. The output is read while waiting, in parallel. Waiting for the child to end and only then reading deadlocks as soon as the output goes past the pipe capacity. Most examples on the internet have this bug, and tests do not show it because tests print little.
  • Ethereal::Process::CLocalListener and Ethereal::Process::CLocalChannel: a named pipe on Windows, a local domain socket on POSIX, with framed messages. This is the agent to service channel. TCP on the loopback uses a port (a machine wide resource), has no identity (any process of any user connects) and brings the firewall in.
  • Ethereal::Process::CSharedMemory: a region visible to more than one process. It gives the mapping, not the synchronization. Crossing that line produces corruption that only shows up under load.
  • Ethereal::Process::CRingChannel: a one producer, one consumer ring over shared memory.
  • Named mutex, semaphore and event that work across processes.

The rules of each part are at the top of process.hpp and ipc.hpp. Two of them are real deadlocks.

ipc.hpp

#include <ethereal/cpp/process/ipc.hpp>

Local channel and shared memory of the Process module.

Two programs on the same machine talking over TCP on 127.0.0.1 works, and it is what almost everyone does. What it costs:

  • A port, a machine wide resource. Two installs of the same product fight over it, and the second fails with a message that explains nothing.
  • No identity. Any process on the computer, of any user, can connect. The control channel between an agent and a local service becomes an entry door, and even a page in the browser can knock on it.
  • The firewall in the middle, with the dialog box that scares the user on the first run.

A named pipe (Windows) or a local domain socket (POSIX) has no port, and the system applies real permissions: by default only the same user gets in. Four rules:

1. The socket file outlives the process. On POSIX the local domain socket is an entry in the file system, and it does not go away when the process dies. A service that crashed leaves the file behind, and the next run fails to bind with 'address already in use'. This module removes the entry before binding and on close. That is why the same test can run twice in a row.

2. A stream gives bytes, not messages. Writing 100 bytes on one side does not mean reading 100 on the other: they may come in two parts, or together with what came next. Code that reads as messages works in tests and fails under load. Here a 4 byte little endian length goes in front, the same framing as the TCP module of this library, on purpose.

3. The announced length is reserved, so it has a limit. A corrupted (or malicious) 4 byte length asks for four gigabytes. Allocating before checking turns one wrong byte into an out of memory crash. CLocalChannel::SetMaxMessageBytes is there for that, and starts at 16 MB. When the limit is passed the channel closes. The header was consumed and the body was not: the stream is out of sync, and the next read would take body for header (any four bytes read as a length). Skipping the body was rejected for the obvious reason: the number to skip is the one that cannot be trusted.

4. On Windows each connection uses one instance of the pipe. A named pipe is not a listening socket: the instance that accepted a connection becomes that connection. Accepting the next one needs another instance. Whoever does not know this writes a server that serves exactly one client and then goes silent.

enum

EIpcError

Ethereal::Process#
C++
enum class EIpcError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  The name is empty or has a character that does not work.
    eInvalidName,

    /// @brief  The listening point or the region could not be created.
    eCreateFailed,

    /// @brief  Could not connect: nobody listening, or the name does not exist.
    eConnectFailed,

    /// @brief  The system refused for permission.
    eAccessDenied,

    /// @brief  Something with that name already exists, and the operation asked to create.
    eAlreadyExists,

    /// @brief  Nothing with that name exists, and the operation asked to open.
    eNotFound,

    /// @brief  The channel is closed, or the other side closed it.
    eClosed,

    /// @brief  The wait timed out.
    eTimeout,

    /// @brief  Sending failed.
    eSendFailed,

    /// @brief  Receiving failed.
    eReceiveFailed,

    /// @brief  The message is over the limit. See rule 3.
    eTooLarge,

    /// The next four belong to the ring and are at the end on purpose. The order
    /// of this enum is ABI: the C layer mirrors the values. Appending keeps every
    /// compiled binary valid. Inserting in the middle would break all of them
    /// silently.

    /// @brief  The ring is full. This is back pressure.
    ///
    /// @details  The spec requires a full ring to return its own status, and not
    ///            drop silently nor block forever. Whoever gets this decides: wait,
    ///            give up, or slow down.
    eFull,

    /// @brief  There is no message to read now.
    eEmpty,

    /// @brief  The other side of the ring died.
    ///
    /// @details  Distinct from @ref EIpcError::eClosed, which is the peer closing
    ///            on purpose. Here its process no longer exists, and whatever is in
    ///            the ring from this point on will not be read by anyone.
    ePeerLost,

    /// @brief  The operation does not fit the role of this side.
    ///
    /// @details  A consumer trying to send, a producer trying to peek, a @c Commit
    ///            without @c Reserve. These are programming mistakes, and a status
    ///            of their own is better than a generic error that sends the reader
    ///            to look in the wrong place.
    eInvalidState,

    /// The next four belong to the synchronization between processes, and are at
    /// the end by the same ABI rule as the ring ones.

    /// @brief  Got the lock, but the previous owner died holding it.
    ///
    /// @details  Whoever gets this has the lock. It is a warning about the data. The
    ///            previous owner fell in the middle of changing it, and what is there
    ///            may be half done.
    ///
    ///            Returning @c eNone here would hide that: the survivor would go on
    ///            over broken data without ever knowing.
    ///
    ///            Whoever repairs it calls @c MarkConsistent. Whoever cannot repair
    ///            it releases the lock without marking it, and it becomes
    ///            @ref EIpcError::eNotRecoverable for everyone.
    eAbandoned,

    /// @brief  The lock was abandoned and nobody declared it consistent.
    ///
    /// @details  Final: no process gets it from here on, and the only way out is to
    ///            destroy it and start again. That is what PTHREAD_MUTEX_ROBUST does
    ///            on Linux, and the rule is imitated on Windows so that both answer
    ///            the same.
    eNotRecoverable,

    /// @brief  The caller does not hold the lock it wants to release.
    eNotOwner,

    /// @brief  The system refused for another reason.
    eSystemError,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong.

struct

SIpcResult

Ethereal::Process#
C++
struct   SIpcResult   final
{
    /// @brief  What went wrong, or eNone.
    EIpcError        eError = EIpcError::eNone;

    /// @brief  The operating system code, when there is one.
    ETL_INT32        iOsCode = 0;

    /// @brief  Description of the failure.
    std::string        sMessage;

    /// @brief  Tells whether the operation succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT    { return eError == EIpcError::eNone; }
};

The result of an IPC operation.

const

DEFAULT_MAX_MESSAGE

Ethereal::Process#
constexpr ETL_UINT32 DEFAULT_MAX_MESSAGE = 16u * 1024u * 1024u;

Default maximum message size: 16 MB.

function

EndpointPath

Ethereal::Process#
std::string EndpointPath( const std::string & sName );

Builds the system name from a logical name.

@c "control" becomes @c "\\\\.\\pipe\\ethereal.control" on Windows and @c "/tmp/ethereal-control.sock" on POSIX. It is a public function because whoever diagnoses needs to know where to look.

sName
Logical name.
The system name.
class

CLocalChannel

Ethereal::Process#

A local connection, with framed messages.

class CLocalChannel final

Movable, not copyable: two copies would mean two closes of the same descriptor, and the second would close the descriptor of something else the system had handed out with the same number.

Send and Receive block. A channel belongs to one thread. To serve many clients, use one thread per channel or the event loop of the Network module.
constructor

CLocalChannel

#
CLocalChannel();

Default constructor. Call Connect, or pass it to Accept.

constructor

CLocalChannel

#
CLocalChannel( CLocalChannel && Other ) noexcept;

Move constructor. Other is left closed.

operator

operator=

#
CLocalChannel & operator=( CLocalChannel && Other ) noexcept;

Move assignment. Closes this channel first. Other is left closed.

function

Connect

#
SIpcResult Connect( const std::string & sName, const ETL_UINT32 uTimeoutMs = 0 );

Connects to whoever is listening with the name sName.

sName
Logical name.
uTimeoutMs
Zero tries once and returns at once.
The result of the operation.
function

Close

#
void Close() noexcept;

Closes the channel.

function

IsOpen

#
bool IsOpen() const noexcept;

Tells whether the channel is open.

function

Send

#
SIpcResult Send( std::span< const std::uint8_t > Data );

Sends a whole message, with the length in front.

Data
Message bytes.
The result of the operation.
function

Receive

#
SIpcResult Receive( std::vector< std::uint8_t > & Out );

Receives a whole message.

Blocks until the whole message arrives, or until the other side closes. That returns EIpcError::eClosed and is not a failure: it is how a conversation ends.

Out
Receives the message.
The result of the operation.
function

SendString

#
SIpcResult SendString( const std::string & sText );

Text shortcuts.

function

ReceiveString

#
SIpcResult ReceiveString( std::string & sOut );
function

SetMaxMessageBytes

#
void SetMaxMessageBytes( const ETL_UINT32 uBytes ) noexcept;

Ceiling of the announced length. See rule 3.

function

MaxMessageBytes

#
ETL_UINT32 MaxMessageBytes() const noexcept;

Current ceiling of the announced length.

function

MessagesSent

#
ETL_UINT64 MessagesSent() const noexcept;

Number of messages sent.

function

MessagesReceived

#
ETL_UINT64 MessagesReceived() const noexcept;

Number of messages received.

class

CLocalListener

Ethereal::Process#
class CLocalListener final
constructor

CLocalListener

#
CLocalListener();

Default constructor. Call Listen before use.

function

Listen

#
SIpcResult Listen( const std::string & sName );

Starts listening on sName.

On POSIX, removes an entry left behind by a previous run before binding. Without it, a service that crashed would keep the next one from starting. That is rule 1, and it is deliberate: the alternative would be asking the operator to delete a file by hand after every crash.

sName
Logical name.
The result of the operation.
function

Accept

#
SIpcResult Accept( CLocalChannel & Out, const ETL_UINT32 uTimeoutMs = 0 );

Waits for a connection.

Out
Receives the connected channel.
uTimeoutMs
Zero waits with no limit.
The result of the operation.
function

Close

#
void Close() noexcept;

Stops listening.

function

IsListening

#
bool IsListening() const noexcept;

Tells whether it is listening.

function

Endpoint

#
const std::string & Endpoint() const noexcept;

System name it is listening on.

class

CSharedMemory

Ethereal::Process#
class CSharedMemory final
constructor

CSharedMemory

#
CSharedMemory();

Default constructor. Call Create, Open or CreateOrOpen before use.

function

Create

#
SIpcResult Create( const std::string & sName, const std::size_t uBytes );

Creates a new region. Fails if it already exists.

Failing when it already exists is the right choice for security: opening a region another process created before means trusting its content, and on a system with many users that is a classic attack vector. Whoever really wants either case has CreateOrOpen, and says so explicitly.

sName
Logical name.
uBytes
Size of the region.
The result of the operation.
function

Open

#
SIpcResult Open( const std::string & sName );

Opens a region that already exists. Fails if it does not exist.

sName
Logical name.
The result of the operation.
function

CreateOrOpen

#
SIpcResult CreateOrOpen( const std::string & sName, const std::size_t uBytes );

Creates, or opens if it already exists.

sName
Logical name.
uBytes
Size of the region.
The result of the operation.
function

Close

#
void Close() noexcept;

Closes the region.

function

IsOpen

#
bool IsOpen() const noexcept;

Tells whether the region is open.

function

IsOwner

#
bool IsOwner() const noexcept;

Tells whether this object created the region.

On POSIX the creator removes the name on close. Otherwise the region outlives the process, like the socket file of rule 1.

function

Data

#
void * Data() noexcept;

Start of the mapped region.

function

Data

#
const void * Data() const noexcept;
function

Size

#
std::size_t Size() const noexcept;

The requested size.

The system rounds up to the page size, and the real region is usually larger. Writing past what was requested may not fail, and that is exactly why this number is the requested one: it is the only one both sides agreed on.

function

Name

#
const std::string & Name() const noexcept;

Logical name of the region.

process.hpp

#include <ethereal/cpp/process/process.hpp>

Child processes and the current process, for the Process module.

Creating a child process and reading its output looks like a three line exercise, and the naive version deadlocks once the output passes a few kilobytes. Six rules, and the first two are deadlocks.

1. Waiting for the child to end before reading its output is a deadlock. The pipe has a finite capacity (4 KB or 64 KB, depending on the system). When it fills, the child blocks on write until someone reads. If the parent is blocked waiting for the child, nobody reads. Most examples on the internet have this bug, and tests do not show it because tests print little. Here each stream is read in parallel with the wait, by a dedicated thread. The price is two threads per process. The alternative was polling per platform (PeekNamedPipe on one side, poll on the other), with a different error path on each and more code to get wrong.

2. The parent must close its write end, or there is never an end of file. A pipe only reports end of file when the last write end closes. The parent creates both ends and gives one to the child. If it keeps its own copy open, the read never ends, even after the child dies.

3. Arguments go as a list. On Windows the system takes a single command line, and the rules for quotes and backslashes are not the expected ones. Joining arguments with spaces breaks on the first path with a space ('C:\Program Files\...'), and breaks in an exploitable way when the argument comes from outside. Here the interface takes the list and QuoteArgument builds the line by the real rules. Outside Windows there is no line: the vector goes straight to the system.

4. Not waiting for the child leaves a zombie. On POSIX a finished process stays in the table until the parent reaps its status. The destructor reaps.

5. Kill does not ask the child to exit. CProcess::Kill is TerminateProcess and SIGKILL: the child stops where it is, with no destructors, no file flush, no cleanup. It is the tool for a hung process, and the wrong one to end a working one.

6. The exit code only exists after waiting. CProcess::ExitCode before CProcess::Wait has no answer, and returning zero would say "it worked". It returns -1, and CProcess::HasExited tells whether the number means something.

enum

EProcessError

Ethereal::Process#
C++
enum class EProcessError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  The process could not be created: missing executable, no
    ///             permission, wrong architecture.
    eSpawnFailed,

    /// @brief  The communication pipes could not be created.
    ePipeFailed,

    /// @brief  The operation needs a running process, and there is none.
    eNotRunning,

    /// @brief  There is already a process in this object.
    eAlreadyRunning,

    /// @brief  The wait timed out and the child is still alive.
    eTimeout,

    /// @brief  The executable path is empty, or the configuration makes no sense.
    eInvalidArgs,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong.

struct

SProcessResult

Ethereal::Process#
C++
struct   SProcessResult   final
{
    /// @brief  What went wrong, or eNone.
    EProcessError    eError = EProcessError::eNone;

    /// @brief  The operating system code, when there is one.
    ETL_INT32        iOsCode = 0;

    /// @brief  Description of the failure.
    std::string        sMessage;

    /// @brief  Tells whether the operation succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT    { return eError == EProcessError::eNone; }
};

The result of a process operation.

struct

SProcessConfig

Ethereal::Process#
C++
struct   SProcessConfig   final
{
    /// @brief  Captures the standard and error output of the child.
    ///
    /// @details  When false, the child inherits the parent streams and writes
    ///            straight to the terminal. Right for an interactive program, wrong
    ///            for one whose result is wanted.
    bool        bCaptureOutput = true;

    /// @brief  Merges the error output into the standard output.
    ///
    /// @details  Keeps the relative order of the two, which separate captures lose,
    ///            and the order is what matters when reading a diagnostic. The price
    ///            is that the two can no longer be told apart.
    bool        bMergeStderr = false;

    /// @brief  Opens the child standard input for writing.
    bool        bRedirectInput = false;

    /// @brief  Working directory of the child. Empty inherits the parent one.
    std::string    sWorkingDirectory;

    /// @brief  Variables to add or override in the child environment.
    std::vector< std::pair< std::string, std::string > >    Environment;

    /// @brief  Inherits the parent environment, with @ref Environment on top.
    ///
    /// @details  When false, the child gets only @ref Environment. That is how a run
    ///            is made reproducible, and it is a security decision: inherited
    ///            variables change the behaviour of whole libraries.
    bool        bInheritEnvironment = true;
};

What can be adjusted when creating a process.

function

QuoteArgument

Ethereal::Process#
std::string QuoteArgument( const std::string & sArgument );

Quotes sArgument by the rules of the Windows command line parser.

The rules are not the expected ones, and are written out in the source: a backslash is only special before a quote, and then the sequence must be doubled. An argument ending in a backslash inside quotes would escape the closing quote.

Outside Windows this is not used to create the process (the argument vector goes straight to the system), but it stays available to build a line for display.

sArgument
The argument to quote.
The quoted argument.
function

BuildCommandLine

Ethereal::Process#
std::string BuildCommandLine( const std::string & sExecutable, const std::vector< std::string > & Args );

Builds the whole command line, with the executable first.

sExecutable
Path of the executable.
Args
The arguments.
The command line.
function

CurrentPid

Ethereal::Process#
ETL_UINT64 CurrentPid() noexcept;

Id of this process.

function

CurrentParentPid

Ethereal::Process#
ETL_UINT64 CurrentParentPid() noexcept;

Id of the process that created this one.

It may no longer exist, and that is not rare: a parent that exits before the child leaves a number the system may already have given to another process. Whoever uses it to talk to the parent must confirm it is the parent, not only that the number answers.

function

ExecutablePath

Ethereal::Process#
std::string ExecutablePath();

Path of the executable of this process. Empty when unknown.

function

CommandLine

Ethereal::Process#
std::string CommandLine();

The command line this process was created with.

On Windows it is a single string, not a vector: the system hands over the text as it came, and splitting it follows the rules of QuoteArgument. On POSIX it is rebuilt from '/proc/self/cmdline', which keeps the arguments separated by zeros. Here they are joined with spaces, without quoting again, so as not to invent a quoting the system never saw.

function

WorkingDirectory

Ethereal::Process#
std::string WorkingDirectory();

Current working directory. Empty when unknown.

function

SetWorkingDirectory

Ethereal::Process#
SProcessResult SetWorkingDirectory( const std::string & sPath );

Changes the working directory of this process.

This is global to the process, and so it is dangerous in a library: another thread opening a relative path at the same moment opens something else. It is here because the spec asks for it. Whoever can pass absolute paths should not call this.

sPath
The new working directory.
The result of the operation.
function

EnvironmentVariable

Ethereal::Process#
std::string EnvironmentVariable( const std::string & sName, bool * pFound = nullptr );

An environment variable of this process. Empty when it does not exist.

Empty and existing are different things, hence pFound: a variable set to empty text is a signal some programs use, and mistaking it for "not there" inverts the decision.

sName
Variable name.
pFound
Receives whether it exists. Null when not needed.
The value of the variable.
function

Environment

Ethereal::Process#
std::vector< std::pair< std::string, std::string > > Environment();

The whole environment of this process, as pairs.

function

ChildProcesses

Ethereal::Process#
std::vector< ETL_UINT64 > ChildProcesses( const ETL_UINT64 uPid = 0u );

The direct children of a process.

This is a snapshot, and it ages while it is read: a child may be born or die between the walk and the decision. Whoever acts on the list must tolerate that one of the ids no longer exists.

uPid
Zero means this process.
The ids of the direct children.
function

KillTree

Ethereal::Process#
SProcessResult KillTree( const ETL_UINT64 uPid, const bool bForce = false, ETL_UINT32 * pKilled = nullptr );

Kills a process and all of its descendants.

The order is bottom up, and that is what matters here. Killing the parent first orphans the grandchildren: the system reparents them to the init process, the link to the tree is gone, and what is left are processes nobody knows the origin of. That is how a "kill the tree" leaves half of it alive. So the whole descendancy is walked first, and the kills go from the leaves to the root.

uPid
Root of the tree.
bForce
False asks to exit, true does not ask.
pKilled
Receives how many processes were killed. Null when not needed.
The result of the operation.
class

CProcess

Ethereal::Process#

A child process, with its pipes.

class CProcess final

The six rules are at the top of this file. The first two are real deadlocks, not hypotheses.

C++
Ethereal::Process::CProcess Child;

if( Child.Start( sExe, { "--mode", "fast" } ).IsOk() )
{
    Child.Wait();

    const std::string sOutput = Child.TakeOutput();
    const int         iCode = Child.ExitCode();
}
constructor

CProcess

#
CProcess();

Default constructor. Call Start to create the child.

function

Start

#
SProcessResult Start( const std::string & sExecutable, const std::vector< std::string > & Args = {}, const SProcessConfig & Config = SProcessConfig() );

Creates the process.

sExecutable
Path of the executable.
Args
The arguments, as a list (rule 3).
Config
Creation options.
The result of the operation.
function

IsRunning

#
bool IsRunning();

Tells whether the child is still running.

Does not block. A child that died but was not reaped yet counts as finished.

function

Wait

#
SProcessResult Wait( const ETL_UINT32 uTimeoutMs = 0 );

Waits for the child to end.

The output is captured in parallel (rule 1). When the time runs out, the child is still alive: the caller decides between waiting more and Kill.

uTimeoutMs
Zero waits with no limit.
The result of the operation.
function

Kill

#
bool Kill();

Ends the child by force. See rule 5.

function

Id

#
ETL_UINT64 Id() const noexcept;

Process id in the system. Zero when there is none.

function

WriteInput

#
bool WriteInput( const std::string & sData );

Writes to the child standard input.

Needs SProcessConfig::bRedirectInput.

sData
Bytes to write.
true when everything was written.
function

CloseInput

#
void CloseInput();

Closes the child standard input.

This is what makes the child see end of file. A child that reads its input to the end waits forever while the parent keeps this end open: the same deadlock as rule 2, the other way around.

function

TakeOutput

#
std::string TakeOutput();

Takes what was captured from the standard output, and empties it.

function

TakeErrorOutput

#
std::string TakeErrorOutput();

Takes what was captured from the error output.

Always empty when SProcessConfig::bMergeStderr is on.

function

HasExited

#
bool HasExited() const noexcept;

Tells whether the child has ended and was reaped.

function

ExitCode

#
ETL_INT32 ExitCode() const noexcept;

The exit code, or -1 when it does not exist yet.

Zero would mean "all went well", so it cannot stand for "unknown" (rule 6). HasExited settles the doubt.

function

WasSignaled

#
bool WasSignaled() const noexcept;

Tells whether the child died by a signal, and not by returning.

Always false on Windows, which has no signals. On POSIX it matters: a process killed by SIGSEGV did not "return" any code.

function

Run

Ethereal::Process#
SProcessResult Run( const std::string & sExecutable, const std::vector< std::string > & Args, std::string & sOutput, std::string & sErrorOutput, ETL_INT32 & iExitCode, const ETL_UINT32 uTimeoutMs = 0 );

ring.hpp

#include <ethereal/cpp/process/ring.hpp>

Shared memory ring of the Process module.

CLocalChannel already gets correctness right: no port, real system permissions, no firewall. It stays the right choice for a control channel. What it does not solve is cost. Every message crosses the kernel twice, once to write and once to read, and each crossing is a system call with a copy. On a channel that carries data in volume, that is the bottleneck.

Here both processes read and write the same memory. On the happy path there is no system call at all: two atomic writes and one copy. The kernel only shows up when one side has to sleep, which is when nobody is in a hurry.

A ring goes one way, on purpose. It has one producer and one consumer. Whoever calls Create is the producer, whoever calls Open is the consumer, and the role never changes. Many producers would need a compare-and-swap on the reservation, which can fail and retry, and the fast path stops being fast. The spec asks for one to one, which fits the use case of an agent and a service. For a two way conversation, open two rings with different names. The benchmark of this module does that to measure the round trip.

Create and Open return SIpcResult. Send, Receive, Reserve, Commit, Peek and Consume return a plain EIpcError, one byte. SIpcResult carries a std::string, which is cheap and useful when creation fails, but the target of the spec is half a microsecond per round trip (about a thousand cycles for everything), and building and destroying a string per operation is a cost that shows inside that budget.

Memory ordering is the weakest that works, and each atomic states its own (the spec forbids seq_cst). The pattern is always the same pair: the publisher writes the data and then stores the index with release. The consumer loads the index with acquire and then reads the data. Without the pair, the other side sees a new index pointing at old bytes.

The index of the other side is cached locally. Reading the peer index on every operation pulls its cache line here and takes it away from the peer, and two processes on different cores would bounce the line back and forth. Each side keeps the last value it read in a private variable, outside the shared memory, and only reads again when the local copy says there is no room (or no data). In steady flow that almost never happens.

const

RING_MIN_CAPACITY

Ethereal::Process#
constexpr std::size_t RING_MIN_CAPACITY = 4096u;

Minimum capacity of a ring.

Below this, the header and the framing weigh more than the data.

const

RING_MAX_CAPACITY

Ethereal::Process#
constexpr std::size_t RING_MAX_CAPACITY = 1024u * 1024u * 1024u;

Maximum capacity of a ring.

One gibibyte. Not a technical limit: asking for shared memory of this size almost always means a unit mistake.

const

RING_FRAMING

Ethereal::Process#
constexpr std::size_t RING_FRAMING = 8u;

Framing bytes carried by each message.

Four for the size and four for the sequence number. The sequence number is not for ordering (a one to one ring is already ordered). It is for detection: a gap seen by the consumer means corruption, or a producer other than the expected one.

class

CRingChannel

Ethereal::Process#

A one producer, one consumer ring over shared memory.

class CRingChannel final
constructor

CRingChannel

#
CRingChannel();

Default constructor. Call Create or Open before use.

function

Create

#
SIpcResult Create( const std::string & sName, const std::size_t uCapacity );

Creates the ring and takes the producer role.

Fails if the name already exists, for the same reason CSharedMemory fails: opening what someone else created means trusting its content.

sName
Name of the shared region.
uCapacity
Data bytes. Rounded up to the next power of two, because the index wrap must be a mask and never a division remainder.
The result of the operation.
function

Open

#
SIpcResult Open( const std::string & sName );

Opens an existing ring and takes the consumer role.

sName
Name of the shared region.
The result of the operation.
function

Close

#
void Close() noexcept;

Closes the ring.

function

IsOpen

#
bool IsOpen() const noexcept;

Tells whether the ring is open.

function

IsProducer

#
bool IsProducer() const noexcept;

Tells whether this side is the producer.

function

Capacity

#
std::size_t Capacity() const noexcept;

Data capacity in bytes, already rounded.

function

Reserve

#
EIpcError Reserve( const std::size_t uSize, std::uint8_t ** ppOut ) noexcept;

Reserves contiguous space for one message.

The space is always contiguous, and that costs a decision: when the message does not fit in what is left up to the end of the ring, the producer writes a skip mark and starts again at zero. Splitting the message in two would force the reader to stitch it, and the zero copy read would be gone. The price of the skip is wasting the tail of the ring now and then.

uSize
Data bytes, not counting the framing.
ppOut
Receives the pointer to write to.
EIpcError::eNone, EIpcError::eFull when it does not fit now, EIpcError::ePeerLost or EIpcError::eInvalidState.
function

Commit

#
EIpcError Commit( const std::size_t uSize ) noexcept;

Publishes what was reserved.

uSize
Must be the same size that was reserved.
EIpcError::eNone, or the reason it failed.
function

Peek

#
EIpcError Peek( const std::uint8_t ** ppOut, std::size_t * pSize ) noexcept;

Points to the next message, without copying or consuming it.

ppOut
Receives the pointer to the message data.
pSize
Receives the message size.
EIpcError::eNone, or EIpcError::eEmpty when there is nothing.
function

Consume

#
EIpcError Consume( const std::size_t uSize ) noexcept;

Discards the message returned by Peek.

uSize
Size returned by Peek.
EIpcError::eNone, or the reason it failed.
function

Send

#
EIpcError Send( const std::uint8_t * pData, const std::size_t uSize, const ETL_UINT64 uTimeoutNanos ) noexcept;

Sends a message, waiting until it fits.

The wait is adaptive: it spins a little with the pause instruction, then yields the processor, and only then really sleeps in the kernel. It never sleeps right away and never spins forever. One wastes latency, the other wastes energy.

pData
Message bytes.
uSize
Message size.
uTimeoutNanos
Zero means do not wait: returns eFull at once. The maximum of ETL_UINT64 means wait forever.
EIpcError::eNone, or the reason it failed.
function

Receive

#
EIpcError Receive( std::uint8_t * pOut, const std::size_t uOut, std::size_t * pWritten, const ETL_UINT64 uTimeoutNanos ) noexcept;

Receives a message into the caller's buffer.

pOut
Output buffer.
uOut
Size of the output buffer.
pWritten
Receives the message size. When the buffer is too small, receives the size needed and the message is not consumed.
uTimeoutNanos
Same convention as Send.
EIpcError::eNone, or the reason it failed.
function

PeerAttached

#
bool PeerAttached() const noexcept;

Tells whether the other side has opened the ring.

function

PeerLost

#
bool PeerLost() const noexcept;

Tells whether the other side died.

Required by the spec, for a practical reason: without death detection, a producer that fills the ring after its consumer fell spins forever in a process nobody will kill.

Detection has two legs. The first is a heartbeat: each side increments a counter in the shared memory when it operates. The second asks the system whether that process id still exists, because a live but idle peer also stops beating, and calling it dead for that would be a false positive.

Only the second leg decides. The first one avoids asking the system all the time, which is expensive.

function

MessagesSent

#
ETL_UINT64 MessagesSent() const noexcept;

Number of messages sent by this side.

function

MessagesReceived

#
ETL_UINT64 MessagesReceived() const noexcept;

Number of messages received by this side.

function

Wraps

#
ETL_UINT64 Wraps() const noexcept;

Number of times the producer had to skip the tail of the ring.

It goes into the benchmark report because it explains the number: a message pattern that falls badly against the capacity skips a lot and wastes space, and without this count it would look like "the ring is slow".

sync.hpp

#include <ethereal/cpp/process/sync.hpp>

Synchronization between processes, for the Process module.

The whole problem of this file is one: the owner dies while holding the lock. Inside one process this almost never happens (if the thread died, the process died, and the lock went with it). Between processes it is the normal case: the agent crashes, the service is killed by the task manager, the container is restarted, and on the other side someone waits for a lock that is never released.

The spec is explicit: "Robust mutex semantics on Linux (PTHREAD_MUTEX_ROBUST) so a crashed holder does not deadlock the survivor, with the equivalent abandoned-mutex handling on Windows."

Both systems already unlock by themselves. The hard part is reporting that the data may be broken. Windows returns WAIT_ABANDONED and hands over the lock. Linux, with a robust mutex, returns EOWNERDEAD and hands over the lock. In both cases the waiter becomes the owner. Both also warn, and that warning is what almost every library throws away: 'if( r == WAIT_OBJECT_0 || r == WAIT_ABANDONED ) return ok;'. The lock works, the program goes on, and the survivor works over a structure the dead one left half done.

Here the warning goes through: EIpcError::eAbandoned means you have the lock and the data may be half done. Whoever can repair it calls CNamedMutex::MarkConsistent. Whoever cannot releases it without marking, and the lock becomes EIpcError::eNotRecoverable for everyone. That is what Linux does, and here Windows does it too.

The limit of the semaphore is declared. The named semaphore has no robust version anywhere. A process that dies after taking a unit and before giving it back loses that unit forever. There is nothing to repair: it is the design of the object, not a bug of this library. Whoever needs robustness uses the mutex.

enum

EOpenMode

Ethereal::Process#
C++
enum class   EOpenMode : ETL_UINT8
{
    /// @brief  Creates it if it is not there, opens it if it is.
    eCreateOrOpen = 0,

    /// @brief  Creates it, and fails if it is already there.
    ///
    /// @details  For whoever needs to know it is the first one, typically the one
    ///            that will initialize the shared memory the lock protects.
    eCreateNew,

    /// @brief  Opens it, and fails if it is not there.
    eOpenExisting
};

How to open a named object.

function

SyncObjectPath

Ethereal::Process#
std::string SyncObjectPath( const std::string & sName );

System path of a synchronization object with that name.

@c "state" becomes @c "Local\\ethereal.sync.state" on Windows and @c "/ethereal-sync-state" on POSIX. Public for the same reason as EndpointPath: whoever diagnoses needs to know where to look.

The prefix matters. Without a namespace of its own, two applications that pick "state" share the lock without knowing, and the symptom is a stall neither of them can explain.

sName
Logical name.
The system path.
class

CNamedMutex

Ethereal::Process#

A lock that works across processes and survives the death of its owner.

class CNamedMutex final

Movable, not copyable: two copies would be two closes of the same descriptor.

Not reentrant, by choice. Windows gives reentrancy for free and Linux does not. Imitating either would need counting recursion by hand, and the count would have to live in the shared memory, where a dead process would leave it wrong. Locking twice returns EIpcError::eInvalidState on both systems, a programming mistake that shows at once.
constructor

CNamedMutex

#
CNamedMutex();

Default constructor. Call Open before use.

constructor

CNamedMutex

#
CNamedMutex( CNamedMutex && Other ) noexcept;

Move constructor. Other is left closed.

operator

operator=

#
CNamedMutex & operator = ( CNamedMutex && Other ) noexcept;

Move assignment. Closes this object first. Other is left closed.

function

Open

#
SIpcResult Open( const std::string & sName, const EOpenMode eMode = EOpenMode::eCreateOrOpen );

Opens the lock with that name.

sName
Logical name.
eMode
Create, open, or either.
The result of the operation.
function

Close

#
void Close();

Releases the object. If the lock is held by us, unlocks it.

function

IsOpen

#
bool IsOpen() const noexcept;

Tells whether the object is open.

function

IsOwner

#
bool IsOwner() const noexcept;

Tells whether we created it.

function

Lock

#
EIpcError Lock( const ETL_UINT64 uTimeoutNanos ) noexcept;

Locks, waiting up to uTimeoutNanos.

uTimeoutNanos
Zero means do not wait. The maximum of ETL_UINT64 means wait forever. Same convention as the ring.
EIpcError::eNone when it went well. EIpcError::eAbandoned when we have the lock and the previous owner died holding it (see the file header). EIpcError::eNotRecoverable when it is lost for good. EIpcError::eTimeout, EIpcError::eInvalidState.
function

TryLock

#
EIpcError TryLock() noexcept;

Locks without waiting. Same as Lock( 0 ).

function

Unlock

#
EIpcError Unlock() noexcept;

Unlocks.

EIpcError::eNotOwner when the caller does not hold it.
function

MarkConsistent

#
EIpcError MarkConsistent() noexcept;

Declares that the protected data makes sense again.

Only after EIpcError::eAbandoned, and only with the lock held. Without this, releasing an abandoned lock leaves it EIpcError::eNotRecoverable for every process. That is the right behaviour: the opposite would pass broken data to the next one without a word.

function

IsHeld

#
bool IsHeld() const noexcept;

Tells whether this lock is held by us, now.

class

CNamedSemaphore

Ethereal::Process#
class CNamedSemaphore final
constructor

CNamedSemaphore

#
CNamedSemaphore();

Default constructor. Call Open before use.

constructor

CNamedSemaphore

#
CNamedSemaphore( CNamedSemaphore && Other ) noexcept;

Move constructor. Other is left closed.

operator

operator=

#
CNamedSemaphore & operator = ( CNamedSemaphore && Other ) noexcept;

Move assignment. Closes this object first. Other is left closed.

function

Open

#
SIpcResult Open( const std::string & sName, const ETL_UINT32 uInitial = 0u, const EOpenMode eMode = EOpenMode::eCreateOrOpen );

Opens the semaphore with that name.

sName
Logical name.
uInitial
Initial count. Only applies on creation: opening one that already exists inherits its count, and passing another one here does not change it.
eMode
Create, open, or either.
The result of the operation.
function

Close

#
void Close();

Releases the object.

function

IsOpen

#
bool IsOpen() const noexcept;

Tells whether the object is open.

function

IsOwner

#
bool IsOwner() const noexcept;

Tells whether we created it.

function

Acquire

#
EIpcError Acquire( const ETL_UINT64 uTimeoutNanos ) noexcept;

Takes one from the count, waiting up to uTimeoutNanos.

function

Release

#
EIpcError Release( const ETL_UINT32 uCount = 1u ) noexcept;

Adds uCount to the count.

class

CNamedEvent

Ethereal::Process#
class CNamedEvent final
constructor

CNamedEvent

#
CNamedEvent();

Default constructor. Call Open before use.

constructor

CNamedEvent

#
CNamedEvent( CNamedEvent && Other ) noexcept;

Move constructor. Other is left closed.

operator

operator=

#
CNamedEvent & operator = ( CNamedEvent && Other ) noexcept;

Move assignment. Closes this object first. Other is left closed.

function

Open

#
SIpcResult Open( const std::string & sName, const bool bManualReset = false, const EOpenMode eMode = EOpenMode::eCreateOrOpen );

Opens the event with that name.

The mode only applies on creation, like the semaphore count. Opening one that already exists inherits its mode.

sName
Logical name.
bManualReset
true: once set, it stays set until someone resets it, and all waiters pass. false: each Set releases one waiter, and the event resets by itself.
eMode
Create, open, or either.
The result of the operation.
function

Close

#
void Close();

Releases the object.

function

IsOpen

#
bool IsOpen() const noexcept;

Tells whether the object is open.

function

IsOwner

#
bool IsOwner() const noexcept;

Tells whether we created it.

function

IsManualReset

#
bool IsManualReset() const noexcept;

Tells whether the event is manual reset.

function

Set

#
EIpcError Set() noexcept;

Sets the event.

function

Reset

#
EIpcError Reset() noexcept;

Resets the event. No effect in automatic mode.

function

Wait

#
EIpcError Wait( const ETL_UINT64 uTimeoutNanos ) noexcept;

Waits until the event is set, or up to uTimeoutNanos.

class

CMutexGuard

Ethereal::Process#
class CMutexGuard final
constructor

CMutexGuard

#
CMutexGuard( CNamedMutex & Mutex, const ETL_UINT64 uTimeoutNanos ) noexcept : m_pMutex( &Mutex ) , m_eStatus( Mutex.Lock( uTimeoutNanos ) )

Locks the mutex.

Mutex
The mutex. Must outlive the guard.
uTimeoutNanos
Same convention as CNamedMutex::Lock.
function

Status

#
EIpcError Status() const noexcept

What Lock returned. Read it.

function

Held

#
bool Held() const noexcept

Tells whether we have the lock. Also true when it came abandoned.