What it does
- Zero-copy SPSC ring between processes that survives the death of either side
- Named lock, semaphore and event. An abandoned lock surfaces as an error
- Same behavior on Windows and Linux, poisoned lock included
- Terminates a process tree from the leaves to the root
Known limits
- Acceptance numbers (round trip, throughput, spawn cost) have not been measured yet. No descriptor passing
Report for the cpp/process module, against spec 04.
---
What exists
| piece | header | oracle it was checked against |
|---|---|---|
| create and wait for child processes | process.hpp | a child that the test itself spawns, with known output |
| local channel with framed messages | ipc.hpp | round trip between two processes |
| shared memory | ipc.hpp | write at one end and read at the other |
| zero-copy SPSC ring | ring.hpp | two processes, and the death of one of them |
| named lock, semaphore and event | sync.hpp | a child killed while holding the lock, and a marker left half written |
| the current process, and the tree | process.hpp | the path must end in this program's name, and the child we spawned must be in the list of our children |
| the C layer | c/process/process.h | compiled as C11 and C17, and the ring's zero-copy surface crosses over in full |
Test suites: process.ring, process.sync (77 checks) and process.cabi / process.cabi.c17 (66). The whole ctest run 78/78 on Windows x64, Debug and Release.
When this batch was written, what it added had not gone through any compiler on Linux. The paths for robust
pthread_mutex,shm_open,sem_open,getppid,/proc/<pid>/statandkillwere written on a Windows machine. The first run on Linux came later, and is described in "The named lock on Linux", further below.
---
The audit against spec 04, and what it found
The ring, which the spec calls "the headline feature", was already done and measured. What was missing was all the rest that the spec lists by name:
| what the spec asks for | was it there? |
|---|---|
| "Cross-process synchronization: named mutex, named semaphore, named event" | none of that existed |
| "Robust mutex semantics on Linux, with the equivalent abandoned-mutex handling on Windows" | did not exist |
Pid, ParentPid, ExecutablePath, CommandLine, Environment, WorkingDirectory | did not exist |
*"Child enumeration and process tree walk (KillTree)"* | did not exist |
| the C layer, "needs to be complete, not partial" | **zero extern "C" functions** |
---
The synchronization problem is a single one: the owner dies holding the lock
Within 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 is left waiting for a lock that will never be released again.
The hard part is saying that the data may be broken
Both systems already unlock the lock on their own. Windows returns WAIT_ABANDONED and hands over the lock. Linux, with the robust lock, returns EOWNERDEAD and hands over the lock.
Both also warn, and that warning is what almost every library throws away. The typical code is if( r == WAIT_OBJECT_0 || r == WAIT_ABANDONED ) return ok; and that is it: the lock works, the program goes on, and the survivor works on a structure that the dead process left half written.
Here the warning gets through. EIpcError::eAbandoned means you have the lock, and the data may be half written:
CMutexGuard G( Mutex, ETL_UINT64_MAX );
if( G.Status() == EIpcError::eAbandoned )
{
RepairWhatIsThere();
Mutex.MarkConsistent();
}
else if( !G.Held() )
{
return;
}The guard does not hide that state, and that is why it has Status() instead of just working. A guard that swallowed it would bring back the defect that the entire file exists to avoid.
The poison is built, because Windows does not have it
On Linux, a robust lock released without pthread_mutex_consistent becomes ENOTRECOVERABLE forever: nobody can take it again. Windows does not have that step. Whoever takes the lock next does not even learn that there was an abandonment.
Without doing anything, the same code would behave in opposite ways: on Linux the lock would close forever, and on Windows the next one would carry on over broken data, without a word. One of the two has to change, and the one that changes is the one that does not warn.
So there is a state word in a shared region next to the lock, with three values: normal, suspect and lost. An aligned 32-bit write cannot come out half done, and so a process that dies in the middle of this state machine does not leave the state inconsistent.
A divergence that only the test machine caught: reentrancy
The Windows lock is reentrant per thread. The Linux one is not. Two CNamedMutex with the same name, taken by the same thread, both succeeded on Windows: the system sees the owner, sees that it is the same thread, and counts recursion. On Linux, the same code returns EDEADLK or hangs.
The same program gave opposite results on the two systems, and the author would write whatever their own machine let through. The module's per-object guard was not enough: it is per object, and there were two objects. The fix was to store who holds it (process and thread) in the state region and refuse the second request from the same thread.
What cannot be emulated is declared
The named semaphore has no robust version anywhere. A process that dies after lowering the count and before restoring it loses that unit forever. There is nothing to fix: it is the design of the object. Whoever needs robustness uses the lock.
And POSIX has no named event. Windows has CreateEventW with both reset modes. On POSIX it is built with a pthread_mutex_t plus a pthread_cond_t, both PTHREAD_PROCESS_SHARED, plus a flag. That is why the reset mode only applies at creation: it lives in the shared region, written by the creator.
---
The test that matters here is the one that kills a process
A cross-process lock that is only exercised by well-behaved processes is not tested. The case it exists to solve is this one:
- the child takes the lock.
- the child is killed, without releasing anything.
- the parent must be able to get the lock, and must know that the data may be broken.
The oracle is not self-referential. The child writes the first of two numbers that must be equal, signals that it took the lock, and is killed before writing the second. The survivor sees the two as different, which proves that "the data may be broken" is not a figure of speech:
ok the child locked the lock, and said so through shared memory
ok the survivor GETS the lock, and is warned of the abandonment
ok and the data ARE really half written, which is what the warning meant
ok releasing without declaring consistency leaves it LOST for everyone
ok and it stays lost, instead of healing by itself
ok declaring consistency while holding the lock passes
ok and after that it is a normal lock againAnd there is the counterpart that catches the opposite. A lock that always returned eAbandoned would also pass the dead-child test. That is why there is a second child, which takes, releases and exits peacefully, whose lock must come back clean and whose marker must be intact. It runs first, on purpose.
---
Killing the tree from the bottom up, and why the order decides everything
Killing the parent first leaves the grandchildren orphaned: the system reassigns them to the init process, the link to the tree disappears, and what remains are processes that nobody knows the origin of. That is how a "kill the tree" leaves half of it alive.
So the entire descendant set is walked first, and the killing goes from the leaves to the root. There is a ceiling of 4096, because a tree with a cycle (which should not exist, and does exist when an identifier is reused) would give an endless loop.
Killing the tree of the current process is refused. Zero means "this process" in the whole rest of the module, and here that would be silent suicide.
On Linux, the process name is in parentheses and may contain spaces
/proc/<pid>/stat has the executable name in the second field, in parentheses, and it may contain spaces, and even a parenthesis. Splitting the line on spaces, which is what almost everyone writes, misaligns all the following fields and reads the state as if it were the parent. Here the code looks for the last ) and reads from there onward.
On Windows the parent is not in a cheap place
There is no getppid. What there is, is the field in the process snapshot, which requires walking the entire list until it finds the current process. That is what CurrentParentPid does, with the note written in the code so that nobody calls it in a loop.
---
The C layer: the ring crosses over with the full zero-copy surface
The spec is explicit: "The ring channel gets the full zero-copy surface, because a C consumer wants the fast path too." The expected consumers are C# and Rust, and what they want from this module is the ring, more than the convenience. A wrapper that only exposed Send and Receive with a copy would give them a channel slower than the one they already have.
So Reserve/Commit and Peek/Consume cross over, with the pointer pointing into the ring and no copy at all in between. The check that matters is the round trip through that path, with the bytes compared on the other side.
The status codes are declared twice (enum class in C++, #define in C), and only the static_assert checks force the two to agree. Without them, adding a status in the middle of the enum would renumber all the following ones, and the C side would start reading "timed out" where C++ said "permission denied". Both compile, both run, and nobody notices. That is why the new statuses in this step were appended at the end of the enum, with the rule written next to it.
**And new can throw.** An exception that crosses an extern "C" boundary is undefined behavior, and the typical symptom is the process disappearing without a trace. The functions that construct objects catch the exception and return null.
**The iStructSize of the creation parameters has a purpose.** The structure arrives zeroed by a memset, which is what a C caller writes first, and without the guard the module would read fields that nobody filled in. A zero iStructSize is refused, and the test machine checks that.
---
Two defects of my own, which the test machine caught
Reentrancy, described above. That one was in the code, and came from the two platforms disagreeing.
And one in the test, which was measuring the race condition instead of the tree. The child it spawned for KillTree was the "polite" one, which exits within milliseconds. When KillTree arrived, the process no longer existed, and the test failed for not having killed anyone. There is now a child that only sleeps.
---
The floor of a wait, and the unit in which the system counts time
A check required that Acquire with a 50 ms deadline on a zeroed semaphore take at least 40 ms as measured. It exists for a good reason, and that reason still holds:
Without it, an implementation that returned
eTimeoutimmediately would pass, and whoever relied on the wait would spin at one hundred percent of a core.
But 40 out of 50 is asking for 80% of a deadline whose unit is almost a third of it. The Windows wait clock advances on the scheduler tick, 15.6 ms: a 50 ms wait wakes on the tick that covers it and, depending on the instant it started, the time measured by a fine-grained clock can fall well below 50.
It failed once in fourteen complete runs in Debug with --parallel 8.
The floor became 25 ms, half the deadline. What the check means to say, "it did not give up immediately", is still said, and is still an enormous distance from the zero it exists to catch. The measured number is now printed, because without it the next failure would again be a name with no measurement.
---
The named lock on Linux, and the errno that is not stable
The first run of the test machine on Linux failed two CNamedMutex checks. Neither of them was about performance, and both were the module's fault.
1. Lock( 0 ) is a trylock, and a trylock on what we ourselves hold gives EBUSY
The module already handled the reentrancy divergence between the platforms (it is written in this README), but the fix had stayed only on the Windows side, with an assumption about the other:
*"On Linux, the robust lock is not recursive and the same code returns
EDEADLKor hangs."*
It returns EDEADLK from pthread_mutex_lock. **From a trylock it returns EBUSY**, the same answer it gives when someone else holds it. The module translated that as eTimeout, and a programming error came out looking like contention.
Owner fields went into the POSIX header, as they already existed on the Windows side. They are checked before trying, and that solves a case that checking afterward did not:
On a non-recursive robust lock, a second
pthread_mutex_lockfrom the same thread hangs forever, and there is no afterward in which to check anything. Asking first turns an eternal hang into an answer.
2. A poisoned lock does not always return the same code
Measured on this machine, on the same lock and with two identical calls:
1st attempt -> iR = 131 (ENOTRECOVERABLE) -> eNotRecoverable
2nd attempt -> iR = 16 (EBUSY) -> eTimeouteTimeout means try again later. The truth is that it can never again be taken: whoever retried because of that code would loop forever.
The module already knew the answer. The state word marked it lost (STATE_LOST) in both cases, and it is Unlock that writes that value when the lock is released without declaring consistency. The Windows branch checks it right after taking the lock. The Linux one did not, and was at the mercy of whichever of the two errno values showed up.
It now checks, like Windows. If the lock was taken anyway, it is released before the answer: leaving a lost lock held would be worse than the error being reported.
The lesson of both is the same: when a module keeps its own shared state precisely so as not to depend on what the platform decides to return, that state must be checked on both sides. Checking it on only one leaves the other depending on what it was meant to avoid.
---
What is still missing from spec 04
- **
CPipeas a first-class type.** The spec asks for an anonymous pair, a named pipe, blocking and non-blocking modes,SetBufferSize, and the broken pipe as its own status. What exists is output capture insideCProcess, andCProcess::Stdin/Stdout/Stderrare not exposed. - **
DrainAll.** The spec asks for it by name against the deadlock of a child that fills one pipe while the parent reads the other. The current capture already does not block. It is the helper the spec names that does not exist. - Descriptor passing (
SCM_RIGHTSon POSIX,DuplicateHandleon Windows). - **Complete
SSpawnParams:**EStdioModeper descriptor, explicitbInheritHandles,bNewProcessGroup,bDetached. What exists is output capture and the working directory. - The acceptance numbers, which remain to be measured against the spec: the 500 ns round trip, the 5 GB/s, the creation cost per platform, the 24 h soak and the sanitizers.
- And the acceptance numbers on Linux. The module's test suites already run there (see "The named lock on Linux"), but none of the numbers above was measured there.