Repository navigation
SharedMemory 2.4.0 runs on Linux and macOS, through a new net10.0 build. New constructors create a buffer or open the one that's already there, and can wait for a buffer to appear. TryRead and TryWrite take a timeout and a cancellation token, and return a status. Reads and writes take array segments and spans. 2.4.0 also fixes the ways a bad argument, a closed buffer or a half-made buffer could crash a process, or stop a circular buffer for every process using it.
Read "Upgrading from 2.3.x" first if you use RpcBuffer, or if you rebuild code that passes null, default or a collection expression to the read and write calls.
Upgrading from 2.3.x
Upgrade both ends of an RpcBuffer channel together
An RpcBuffer from 2.4.0 can't share a channel with one from 2.3.x or earlier (#89). The objects the two ends find each other by have new names, and the packets have a new format. On Windows, a mixed pair fails when you create the second end:
- If 2.3.x started first, the 2.4.0 end throws
InvalidOperationException:Channel "{name}" is in use by an RpcBuffer from SharedMemory 2.3 or earlier, which cannot share a channel with this version. Upgrade both ends. - If 2.4.0 started first, the 2.3.x end throws
FileNotFoundException.
Code compiled against 2.3.x runs with the 2.4.0 DLL, as long as both ends of each channel run 2.4.0.
Code you rebuild
When you rebuild code against 2.4.0, each call binds to the overload it bound to before, with these exceptions:
| Your code | In the builds | Bound to, before | Now |
|---|---|---|---|
A bare null passed to BufferReadWrite.Write or Read, with or without a position, or default without one |
.NET Standard 2.1, .NET 10 | the Action<IntPtr> calls, which then threw NullReferenceException |
compile error CS0121, ambiguous with the byte span calls |
default passed to SharedArray<T>.Write or CopyTo, with or without a start index |
.NET Framework 4 to 4.7 | the array calls, which then threw ArgumentNullException |
compile error CS0121, ambiguous with the ArraySegment<T> calls |
A collection expression, such as [1, 2, 3], passed to BufferReadWrite.Write<T> or Read<T>, or to SharedArray<T>.Write or CopyTo, with or without a position or start index |
.NET Standard 2.1, .NET 10 | the array calls | the span calls, with the same result unless you subclass and override one of the protected virtual array copies in SharedBuffer, which the span calls don't go through |
new RpcBuffer(name, handler, default) |
every build with RpcBuffer |
the buffer capacity, 0, which threw ArgumentOutOfRangeException |
the new constructor that takes RpcBufferOptions, which throws ArgumentNullException |
Buffers shared with 2.3.x
A 2.3.x process and a 2.4.0 process still share a BufferReadWrite, a SharedArray<T> or a CircularBuffer, whichever one creates it. A 2.3.x process doesn't wait for the process creating a buffer to finish, though, so it can still open one half made. Upgrade the processes that open buffers, not only the ones that create them.
Linux and macOS
The net10.0 build runs on Linux x64 and arm64, and on macOS 14.4 or later, so your app needs to target .NET 10 or later there (#40, #61). We test it on Linux, Alpine included, and on macOS on Apple silicon. macOS on Intel should work, but we don't test it. On Linux and macOS the netstandard2.0 and netstandard2.1 builds throw PlatformNotSupportedException, and so does every build on any other platform, such as 32-bit Linux or FreeBSD. Windows gets every build, as before. Platforms has the details.
Every class works between processes. What differs from Windows:
- A name with no prefix, or with
Local\, belongs to your user account rather than your session, so programs started from different terminals or SSH logins find each other. See Names on Linux and macOS. - On Linux a buffer is a file in
/dev/shm. On macOS it's a POSIX shared memory object, with a lock file in/var/tmp. See Where the memory lives. - The library removes the files behind a buffer when the last process using it closes it, and a process that returns from
Mainor callsEnvironment.Exitcloses the buffers it still has open. A process that's killed, crashes, or is stopped by a signal such as SIGTERM or Ctrl+C leaves them until some process next uses the name. Catch those signals and return fromMainso the cleanup runs. The .NET Generic Host does that for you. See When a process ends. - By default, systemd removes a user's files in
/dev/shmwhen that user's last session ends, including buffers still in use. A service running as an ordinary user needs one of the fixes in When users log out. - The two ends of an
RpcBufferchannel find each other whichever .NET 10 patch each one runs on, and whatever itsXDG_RUNTIME_DIRon Linux orTMPDIRon macOS. So a cron job or a service pairs with a program started from your desktop (#102). - When the owner of a channel is killed, the next
RpcBufferon the channel becomes its owner once the old process has exited. If the old opener is still open, every newRpcBufferon the channel throwsIOExceptionuntil that opener is disposed or its process ends.
A round trip between two processes through two CircularBuffers takes about 3 µs on Linux x64. On an M1 Pro it takes about 6 µs, or about 36 µs when macOS runs the processes on the efficiency cores.
Choosing the folder, and sharing between containers
SharedMemoryOptions.UnixDirectory, which CircularBufferOptions and the new RpcBufferOptions also have, puts the files behind a buffer in a folder you choose (#107). On Linux the buffer files go there instead of /dev/shm, and on macOS the lock files go there instead of /var/tmp. Windows checks the value and ignores it, so the same code runs there.
Two containers can then share buffers through a tmpfs folder they both mount, rather than through /dev/shm, which Docker and Podman limit to 64 MB by default. We tested sharing between an Alpine container and an Ubuntu one.
- Every process that shares a buffer or an
RpcBufferchannel has to give the same folder. A process that gives another folder, or none, gets a separate buffer or channel. - The value must be an absolute path, or the constructor throws
ArgumentExceptionon every OS. The library never creates the folder. A missing one throwsDirectoryNotFoundExceptionstraight away, even withOpenTimeoutset. - On Linux, put the folder on a memory-backed file system. On macOS, keep it out of
/tmp, where macOS deletes files whose times are all more than 3 days old, even lock files in use.
See Choosing the folder and Sharing between containers.
New APIs
Example Usage in the README describes each of these, and its examples use TryRead, TryWrite and IsChannelOwner.
Creating or opening, and waiting to open
BufferReadWrite, SharedArray<T> and CircularBuffer have constructors that take a SharedMemoryOptions, or a CircularBufferOptions for a CircularBuffer, in every build (#105).
- With
OpenModeset toSharedMemoryOpenMode.CreateOrOpen, the constructor that takes sizes creates the buffer if the name is free, and otherwise opens the one that's there (#56). That buffer must be the same kind with the same sizes, or the constructor throwsInvalidOperationExceptionnaming both. - If the owner of the buffer it finds has closed it, your instance takes it over and becomes the owner, and
ShuttingDownturns false again in every process. So a producer can restart while its consumer still has the buffer open.CreatedSharedMemoryandIsOwnerOfSharedMemorytell you whether your instance created the buffer, took it over or opened it. - With
OpenTimeoutset, the constructor that takes only a name waits up to that long for the buffer to appear and be ready, instead of throwingFileNotFoundExceptionat once (#6). When the time runs out it throws what it would have thrown without the wait, so yourcatchblocks still work. In every build but the .NET Framework 3.5 one,OpenCancellationTokenstops the wait. SharedBuffer.TryGetInfo(name, out info)tells you the kind, layout version, sizes and state of a buffer without opening it, so you can find out the sizes another process chose.
TryRead and TryWrite
In every build but the .NET Framework 3.5 one, CircularBuffer.TryRead and TryWrite take a TimeSpan timeout and an optional CancellationToken, and return a CircularBufferStatus: Ok, TimedOut, Closed, or for a read TooSmall (#71).
- A
TryReadinto an array too small for the next item copies nothing. It returnsTooSmallwith the size of the item inlength, and leaves the item for the next read.Readstill copies what fits and drops the rest. TryWritewrites all of its source or nothing. A source bigger than a node throwsArgumentException, whereWritewrites what fits.Closedmeans the owner has shut the buffer down and there's nothing left to read or no room to write, or that you closed the instance while the call waited. A loop ofTryReadcan end atClosedwithout checkingShuttingDown.- Both calls notice a cancel within 10 ms on Linux and macOS, or about 15.6 ms on Windows. A cancel never loses an item.
- If your subclass overrides
GetNodeForReading(int),TryReadthrowsNotSupportedException, and so doesTryWriteif it overridesGetNodeForWriting(int).
Lock waits with a timeout and a token
In the same builds, BufferReadWrite and SharedArray<T> have TryAcquireReadLock and TryAcquireWriteLock. Each takes a TimeSpan timeout and an optional CancellationToken, and returns false at the timeout. They work the same gates as AcquireReadLock and AcquireWriteLock, which are not exclusive locks. See Read and write locks. After Close, both throw ObjectDisposedException.
Segments and spans
In the same builds, BufferReadWrite reads and writes an ArraySegment<T> at a position, SharedArray<T> writes one and copies into one at a start index, and TryRead and TryWrite take one too. In the .NET Standard 2.1 and .NET 10 builds they also take spans. So you no longer copy part of an array, or a span, into a new array first (#75, #34). Segments and spans copy elements in the same layout as arrays, so a structure written from a span in a .NET 10 process reads the same in a .NET Framework or 32-bit process.
RpcBuffer
IsChannelOwnertells you whether an instance is the owner of the channel, which created it, or the opener, which joined it (#89).RpcBufferOptionsholdsBufferCapacity,BufferNodeCountandUnixDirectory. The capacity defaults to 50,000 bytes and can be 256 bytes to 1 MB, and the node count defaults to 10. Each kind of handler has a constructor that takes it, andnew RpcBuffer(name, options)makes an end with no handler (#107).- A message is no longer limited to 65,535 packets.
- A message the other end doesn't understand gets an error reply at once, so your call returns
Success = falseinstead of waiting out its timeout. - Sending and reading no longer allocate a buffer or a delegate for each packet (#62). A 1 MiB echo allocates about 2 MiB where it allocated about 4 MiB.
Fixes
Reads and writes outside a buffer (#92)
BufferReadWrite and SharedArray<T> check the position and length of every read and write before they copy anything, so a bad position can no longer overwrite the buffer header, run past the end of the buffer into other memory, or crash your process.
- A position outside the buffer throws
ArgumentOutOfRangeException. A copy that starts inside the buffer and runs past its end throwsArgumentException. - A negative length for a pointer copy throws
ArgumentOutOfRangeException. It used to throwOverflowExceptionon the .NET Core builds, and crash the process on the .NET Framework builds. - Creating a
CircularBufferwith anodeBufferSizebelow 1 throwsArgumentOutOfRangeException.
Closing a buffer while it's in use (#93)
CloseandDisposereturn straight away, and the memory stays mapped until the last call running on the buffer returns. ARead(Func)orWrite(Func)callback keeps a valid pointer until it returns, even if it disposes the buffer itself.- A read or write after
CloseorDisposethrowsObjectDisposedExceptionnaming the buffer. It used to throwNullReferenceException, or crash the process.
Leaks (#94)
- A buffer that's never disposed releases its memory when the garbage collector finalises it. Other processes see no change, since only
CloseandDisposesetShuttingDown. - A constructor that fails to open a buffer frees the two events it created before it throws.
- On .NET Framework 3.5, a create that failed because the name was in use kept a handle on the mapping until the garbage collector ran, so the name stayed in use after its holder closed it. 2.4.0 releases the handle at once.
Opening a buffer while its owner is still creating it (#95)
A buffer is visible to other processes before the process creating it has set it up, and 2.3.x could open it half made, with a BufferSize of -16. In 2.4.0 the owner marks the buffer ready once Open() has finished, DoOpen included, and an opener waits for the mark.
- An opener waits up to 1 second, or
OpenTimeoutif you set it, and then throwsInvalidOperationExceptionsaying the buffer is not ready. If the owner fails part way, a waiting opener throws at once. - A buffer created by 2.3.x has no mark. 2.4.0 opens it once 2.3.x has written its size, waiting up to 1 second for the size and, for a
CircularBuffer, up to another second for its nodes. - If your subclass writes to shared memory in its constructor after calling
Open(), an opener can still find that half written. Do that work inDoOpeninstead.
The header also records the layout version and kind of the buffer, in bytes that earlier versions wrote as 0 and never read:
- An opener refuses a buffer from a later version whose layout it can't read, with an
InvalidOperationExceptionthat names the layout version and says to use that version here too. - A
CircularBufferrefuses a buffer that 2.4.0 created as another kind, such as aBufferReadWrite, withInvalidOperationExceptionat once. It used to wait a second, or read the data in the buffer as a ring header.BufferReadWrite,SharedArray<T>and yourSharedBuffersubclasses still open a buffer of any kind, as bytes.
Circular buffer waits and shutdown (#97)
- A read timeout covers the whole call. A waiting reader looks at the buffer every 10 ms, or about 15.6 ms on Windows, so two readers waiting when two items arrive both get one, and a reader woken for an item another reader takes doesn't start its timeout again. Looking costs a little CPU time. In our tests a reader blocked for 5 seconds used about 8 ms of it on Linux and 46 ms on an Apple M1 Pro.
- Once the owner has closed the buffer,
ReadandWritereturn 0 straight away when there's nothing to read or no room, where 2.3.x waited out the timeout. A loop that reads or writes until the owner goes should checkShuttingDown, or it will spin. See Circular buffer readers and capacity. - A
ReadorWritethat's waiting when you close the instance you called it on returns 0, and the next call throwsObjectDisposedException. - A read or write with a timeout of 0 doesn't wait.
Failed and empty writes (#96)
- Every
CircularBufferReadandWriteoverload checks its arguments before it takes a node. A bad array index or length used to take a node and leave it reserved, which stopped reads or writes in every process. A null array or callback throwsArgumentNullException, where it threwNullReferenceException. - An array, pointer or structure write that throws partway posts its node empty, and such a read gives its node back, so the buffer keeps working.
- A write of nothing, such as
Write(new byte[0]), still takes a node. A 2.4.0 reader skips such a node and takes the next item, soReadnever returns 0 for one. A reader on an earlier version doesn't skip it. Write(Func)returns the value from your callback, limited to between 0 and the node size.
Damaged shared memory (#98)
- A
CircularBufferworks out the address of each node from its index, rather than reading it from shared memory. An amount written that's below 0 or above the node size counts as 0 or the node size. - A read or write that finds a read or write position outside the nodes of the buffer throws
InvalidOperationException. So does opening a buffer whose header gives fewer than 2 nodes, nodes of 0 bytes, or nodes that don't fit in the buffer. - One
RpcBufferpacket claiming a huge message can no longer make the receiving process allocate it all at once. The first packet allocates the size of the message or 1 MiB, whichever is smaller, and the array doubles as packets arrive. So a message over 1 MiB allocates up to about twice its size while it arrives, and takes longer. In our tests a 16 MiB call on .NET Framework took about 25 ms, against 5 ms with 2.3.4.
If you subclass CircularBuffer
- An instance places each node buffer by its
NodeBufferOffset. If you override it, every process that uses the buffer must use your subclass. - The protected
GetNodeForReadingskips empty nodes, giving each back throughReturnNode. An override that doesn't call the base method gets no skipping. An override of it or ofGetNodeForWritingthat returns a node outside the buffer makes the read or write throwInvalidOperationException. - Post a node you got from
GetNodeForWritingbefore the buffer closes.
Other fixes
- The
ClientTest,ServerTestandSingleProcessexamples in the repository passed100where a timeout was meant, and it bound tostartIndex. They now name the argument,timeout: 100. If you copied that code, name it in yours too. - The
netstandard2.1build no longer depends onSystem.Reflection.Emit.Lightweight, which it never used.
Obsolete
These still work as before. Code that uses one gets warning CS0618, with a message that says why.
- The protected
BufferWithLocks.WriteWaitEventandReadWaitEvent, andCircularBuffer.DataExistsandNodeAvailable(#91). The library sets them on Windows only, and leaves them null on Linux and macOS. To hold reads back, useAcquireWriteLockandReleaseWriteLock. To hold writes back, useAcquireReadLockandReleaseReadLock. On Windows, the library no longer waits on, signals or disposes a handle that a subclass assigns toDataExistsorNodeAvailable. Using these four becomes an error in 2.5.0, and 3.0 removes them. RpcProtocol.V1.RpcBufferaccepts the value and ignores it, since it has one protocol now, so leave the argument out.RpcProtocolHeaderV1,CircularBuffer.NodeHeaderandCircularBuffer.ReadNodeHeader(),ResponseTaskHelperand itsTimeoutOrCancel, and the unusedSharedMemory.Utilities.ArraySlice<T>andExpandingArray<T>. IntelliSense no longer offers them, and 3.0 removes them. For the sizes of a ring, useNodeCountandNodeBufferSize. Pass a timeout and a cancellation token toRemoteRequestAsyncinstead of callingTimeoutOrCancel. UseArraySegment<T>in place ofArraySlice<T>.
Frameworks in 3.0
2.4.0 still has every build 2.3.4 had, plus net10.0. SharedMemory 3.0 will build for net472, netstandard2.0, netstandard2.1 and net10.0 only, so it will need .NET Framework 4.7.2 or later. Apps on an older .NET Framework can stay on 2.x, which remains on NuGet.
What's Changed
- feat(#40, #61): Linux and macOS support by @justinstenning in #88
- feat(#89)!: RpcBuffer owner and opener, and protocol 2 by @justinstenning in #90
- chore: mark the protected wait-handle properties obsolete by @justinstenning in #91
- fix: buffer and ring safety (#92 to #98) by @justinstenning in #101
- fix: RpcBuffer elects through its own file on Linux and macOS by @justinstenning in #102
- feat(#95): layout marker and ready flag in the shared header by @justinstenning in #103
- docs: README examples as two programs, run in CI by @justinstenning in #104
- feat(#56, #6): options, create-or-open, and opening with a wait by @justinstenning in #105
- chore: obsolete NodeHeader, ResponseTaskHelper and the unused utilities by @justinstenning in #106
- feat: a Unix backing directory, and RpcBufferOptions by @justinstenning in #107
- feat(#71, #75): TryRead and TryWrite, cancellation, segments and spans by @justinstenning in #108
- chore: prepare 2.4.0 by @justinstenning in #109
- chore: package description names Linux and macOS by @justinstenning in #110
Full Changelog: v2.3.4...v2.4.0