Server
Represents an immutable server handle and snapshot.
Source and package
- Qualified name
-
LibTmux. Server - Namespace
- LibTmux
- Package
- LibTmux
- Source
- src/LibTmux/Server.cs
-
Description
Thread-safe: the handle is immutable once constructed and may be shared freely, including as a singleton. Every mutating call answers a new handle rather than changing this one.
A handle names the server on one socket, chosen by its
ServerConnectionOptions, rather than the process behind it, so it can be opened before any server is listening. Two handles that reach the same endpoint are equal (Equals()) and hash alike (GetHashCode()). Letting go of a handle never stops the server; disposing anOwnedServerScopedoes.What is on here
A tmux server does a great many things, so this type has a great many members. They fall into a few groups:
- Connecting
- Open a handle without running tmux, then connect it to find the server already listening; connecting never starts one. Take the server this process is already inside, or start one and own it, so that disposing the scope stops it. A connected handle is bound to the server it found, so after tmux restarts its sessions, windows, and panes throw
StaleServerGenerationExceptionrather than reach the new one. - ConnectInside tmuxTimeoutControl mode
- Checking the server
- Ask whether a server is answering, or have the call throw when none is. Inspecting reads the live server without running
InitializeAsync, and answersnullwhen none is listening. Starting the daemon returns no handle, because with tmux's exit-empty default a server holding no sessions exits as soon as it starts. - StartWhich serverWhich tmux
- Finding one thing
- Read one session, window, or pane by its identifier. The Get methods throw
TmuxObjectNotFoundExceptionwhen it is absent; the Find methods answernullinstead, but only after a read that succeeded. Ask by name whether a session exists, or find a client by name. - By name
- Listing everything
- Read every session, window, pane, or client on the server. Each throws when the listing fails, so an outage never reads as an empty server. A capture reads one listing per level, down to the depth asked for, and answers a new handle whose relations then answer without another command; clients are not part of a capture.
- Querying things and getting around
- Searching hands tmux an
UnsafeTmuxFilter, so rows it rejects never become objects; a malformed filter returns no rows rather than an error, and searching clients needs tmux 3.4. To filter what has already been read, give theMatchingextension inQueryExtensionsa C# predicate; the same class translates a predicate into a portable document and plans it for tmux to evaluate. Moving between levels of a capture never reaches tmux, and a relation the capture did not read throwsIncompleteSnapshotExceptionrather than reading as empty. - Translate and planFocused
- Changing things
- Create a session, with the identifiers of its first window and pane in the receipt form, or inside a scope that stops it when disposed. Creating a session under a name already taken throws
TmuxSessionExistsException. Stopping the server counts one that is already gone as success; windows and panes change throughSession,Window, andPane. - Options and hooks
- The server's options, its global hooks, and the environment new sessions inherit are objects of their own:
TmuxOptions,TmuxHooks, andTmuxEnvironment. Server options belong to the daemon rather than to anything inside it, so nothing is targeted. tmux has no server hook table, so the global one serves as the server's. - Everything else tmux keeps
- Cancelling a shell command stops the call from waiting, not the command from running. Prefer an open wait channel to a plain wait whenever the wait has a deadline, because cancelling a plain wait leaves its queue entry in tmux before 3.8, and that entry takes the next signal. A layout check at parse time never contacts tmux; the check against a server also catches names that only some tmux versions accept.
- ConfigurationChannelsCommands and promptsAccess
- Things that need a terminal
- Menus, command prompts, and confirmations draw on an attached client, and switching the caller's own client acts on one; tmux refuses all four when none is attached. Attaching makes the client instead, so it needs a terminal of its own. The other client commands take the name of a client, which the client listing returns.
- SwitchAttachRefresh or suspendLock or detach
- Raw commands
- Anything tmux can do that is not here runs as a raw command, one at a time with its result handed back, or several chained into one tmux invocation. A process the library cannot dispatch itself, such as an interactive attach, takes the endpoint arguments to select the endpoint and a guarded command line that runs only while the server generation is still current.
Examples
Distinguish an endpoint handle from a discovered server. Connection discovery returns an immutable replacement without capturing child relations. Use Linux or macOS with tmux 3.3a or newer, the .NET 10 SDK or newer, and the .NET 8 and 10 runtimes. In an empty directory, save this project as
Example.csproj. It references the 0.1.1 release ofLibTmuxon NuGet: View sourceExample.csproj <Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net8.0;net10.0</TargetFrameworks><LangVersion>12.0</LangVersion><Nullable>enable</Nullable><ImplicitUsings>disable</ImplicitUsings><EnableDefaultCompileItems>false</EnableDefaultCompileItems><TreatWarningsAsErrors>true</TreatWarningsAsErrors><AnalysisLevel>10-recommended</AnalysisLevel></PropertyGroup><ItemGroup><Compile Include="Program.cs" /><PackageReference Include="LibTmux" Version="[0.1.1]" /></ItemGroup></Project>Save this complete program as
Program.cs. It creates a private server;await usingdisposes its owned scopes after success, cancellation or failure. The complete file contains explicit imports, a top-level async entry point and a cancellation deadline. View sourceProgram.csComplete program using System;using System.IO;using System.Threading;using LibTmux;if (OperatingSystem.IsWindows()){throw new PlatformNotSupportedException("This example requires tmux on Linux or macOS.");}using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));CancellationToken token = deadline.Token;string? testTmux = Environment.GetEnvironmentVariable("LIBTMUX_TEST_TMUX");string? configured = !string.IsNullOrWhiteSpace(testTmux)? testTmux: Environment.GetEnvironmentVariable("LIBTMUX_TMUX");string binary = string.IsNullOrWhiteSpace(configured) ? "tmux" : configured;using TemporaryDirectory socketRoot = new();ServerConnectionOptions options = new(){SocketPath = Path.Combine(socketRoot.FullName, "tmux.sock"),ConfigurationFile = "/dev/null",TmuxBinaryPath = binary,};// Open records the endpoint without running tmux or reading its state.Server endpoint = Server.Open(options);if (endpoint.IsMaterialized){throw new InvalidOperationException("Open must not discover a server.");}await using OwnedServerScope owned = await Server.CreateOwnedAsync(options, token);await using OwnedSessionScope session = await owned.Value.CreateOwnedSessionAsync(new NewSessionRequest { Name = "demo", Command = "/bin/cat" }, token);// Connect discovers the live daemon and returns a new materialized handle.Server connected = await endpoint.ConnectAsync(token);Server sameEndpoint = await Server.ConnectAsync(options, token);if (!connected.IsMaterialized || !sameEndpoint.IsMaterialized || endpoint.IsMaterialized){throw new InvalidOperationException("Connecting must leave the original handle unchanged.");}if (connected.Generation != sameEndpoint.Generation || connected.Sessions.IsCaptured){throw new InvalidOperationException("Connection discovery must not capture the hierarchy.");}Console.WriteLine("Open records an endpoint; Connect discovers the running server.");Console.WriteLine("The original handle stays unmaterialized; relations remain uncaptured.");internal sealed class TemporaryDirectory : IDisposable{private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("libtmux-example-");public string FullName => _directory.FullName;public void Dispose() => _directory.Delete(recursive: true);}Build the project and run both supported frameworks. Each program checks its result and exits unsuccessfully after an unhandled error:
Terminal window $ dotnet build Example.csproj --configuration Release && \dotnet bin/Release/net8.0/Example.dll && \dotnet bin/Release/net10.0/Example.dllExpected program output from each framework:
Open records an endpoint; Connect discovers the running server.The original handle stays unmaterialized; relations remain uncaptured.
Properties16
| Name | Type | Description |
|---|---|---|
| Sessions | Captured | Gets the sessions this handle captured. |
| Windows | Captured | Gets the windows this handle captured, across every session. |
| Panes | Captured | Gets the panes this handle captured, across every window. |
| Clients | Captured | Gets the clients this handle captured. |
| Buffers | Tmux | Gets the paste buffers of this server. |
| Hooks | Tmux | Gets the hooks of this server. |
| Options | Tmux | Gets the options of this server. |
| Environment | Tmux | Gets the environment new sessions inherit from. |
| Version | Tmux | Gets the tmux version this handle was checked on. |
| ConnectionOptions | Server | Gets the connection options. |
| DaemonVersion | Tmux | Gets the daemon version read by inspection, or null when it was not acquired. |
| EndpointArguments | IRead | Gets the endpoint selection arguments -- -L, -S, or a configuration file flag -- this handle's connection resolved. |
| Generation | Server | Gets the materialized server generation. |
| IsMaterialized | bool | Gets whether this handle has discovered a live server. |
| Keys | Tmux | Gets the key bindings of this server. |
| SnapshotMetadata | Snapshot | Gets acquisition metadata, or null when this handle was not captured. |
Members61 members
Collections and queries9
- GetCommandsAsync Reads the commands this tmux knows.
- GetSessionsAsync Reads every session on this server.
- GetWindowsAsync Reads every window on this server.
- GetPanesAsync Reads every pane on this server.
- GetClientsAsync Reads the clients attached to this server.
- CaptureSnapshotAsync Reads the server and answers a handle carrying what it found.
- SearchPanesAsync Runs a tmux-side filter over every pane.
- SearchSessionsAsync Runs a tmux-side filter over every session.
- SearchWindowsAsync Runs a tmux-side filter over every window.
Common operations38
- CreateSessionAsync Creates a session.
- KillAsync Stops the tmux server.
- SourceFileAsync Reads a tmux configuration file.
- WaitForAsync Waits on, signals, locks, or unlocks a tmux channel.
- RunShellAsync Runs a shell command and reports what it printed.
- IsAliveAsync Reports whether a tmux server is answering.
- HasSessionAsync Reports whether a session exists.
- GetSessionAsync Reads one session by identifier, throwing when it is absent.
- GetWindowAsync Reads one window by identifier, throwing when it is absent.
- GetPaneAsync Reads one pane by identifier, throwing when it is absent.
- AttachSessionAsync Attaches a client to a session on this server.
- DetachClientAsync Detaches one client.
- StartServerAsync Starts the tmux server without creating a session.
- IfShellAsync Runs one tmux command or another depending on a shell command.
- GetPromptHistoryAsync Reads what has been typed at command prompts.
- ClearPromptHistoryAsync Forgets what has been typed at command prompts.
- ShowCommandPromptAsync Asks a client for input and runs a command with the answer.
- LockAsync Locks every client attached to this server.
- RefreshClientAsync Redraws one client.
- SwitchClientAsync Switches the caller's client to another session.
- ThrowIfDeadAsync Throws unless a tmux server is answering.
- Chain Begins a chain that runs its commands in one tmux invocation.
- FromEnvironment Returns the server whose pane this process was spawned in.
- GetMessagesAsync Reads what the server has been logging.
- ConfirmBeforeAsync Asks a client to confirm before running a command.
- DisplayMessageAsync Shows a message on a client.
- LockClientAsync Locks one client.
- SuspendClientAsync Suspends one client.
- KillSessionAsync Stops one session.
- GetAttachedSessionsAsync Reads every session with at least one attached client.
- DetachAllClientsAsync Detaches every client except one.
- CreateOwnedAsync Starts a server and takes ownership of it.
- EnterControlModeAsync Starts a tmux control client and keeps it running.
- OpenWaitChannel Opens a wait on a channel that survives a timed attempt.
- ConnectAsync Connects to a configured tmux endpoint.
- CreateOwnedSessionAsync Creates a session and takes ownership of it.
- FindSessionAsync Reads one session by identifier, returning null when it is absent.
- Open Opens an unmaterialized server connection handle.
Other members14
- BuildGuardedCommandLine Builds the argument vector for a raw tmux invocation that only takes effect while the named server generation is still current.
- ConfigureAccessAsync Grants or withdraws another user's access to this server.
- CreateSessionWithReceiptAsync Creates a session and returns its initial window and pane identities.
- Equals
- ExecuteCommandAsync Executes one raw tmux command.
- FindPaneAsync Reads one pane by identifier, returning null when it is absent.
- FindWindowAsync Reads one window by identifier, returning null when it is absent.
- GetHashCode
- InspectAsync Reads the live endpoint identity without running its initializer.
- IsValidLayoutCandidate Checks a layout's syntax without contacting a server.
- SearchClientsAsync Runs a tmux-side filter over every attached client.
- ShowMenuAsync Shows a menu on a client.
- ValidateLayoutsAsync Checks layouts before a workspace changes the server.
- Within Returns this server with every command bounded by a timeout of the caller's choosing.
No members of Server match . The filter searches only this type. Search the whole API.
Order: the accessors that walk the hierarchy, the operations the ports share, then the rest.
Guides
task materialPages that discuss Server.
- Guides
In other ports
task equivalence 22 other ports mappedSource-verified mappings for A tmux server. A mapping says these APIs perform the same task. It does not say they share defaults, errors or completion: check each page.
| Port | API | Differs from C# |
|---|---|---|
| C# | Lib Represents an immutable server handle and snapshot. | This page |
| Python | libtmux tmux(1) Server [server_manual]. | None recorded in the model |
| Ruby | Lib Connects to an existing endpoint. Closing retires clients, never the daemon. | None recorded in the model |
| Lua | libtmux | None recorded in the model |
| PowerShell | Lib Construct a tmux endpoint handle without contacting it. | 2 overloads This cmdlet constructs a shared .NET LibTmux.Server handle without contacting tmux. |
| Julia | Lib Describe a tmux endpoint without contacting it. Supply exactly one socket selector. A description does not own a daemon or any sessions. Use from_env to opt into the ambient tmux endpoint. | |
| Erlang | tmux Open tmux endpoints and execute explicit command values. | open/1 observes an existing daemon and starts an endpoint owner. Domain rows remain immutable values. |
| Elixir | Lib An explicit local tmux server descriptor. | Server describes an existing server by executable and socket. It neither connects nor reserves the server’s identity. |
| Haskell | Lib Start, observe and change a tmux daemon through a scoped handle. | LibTmux.Server owns the Server handle. withOwnedServer starts and retires a private daemon; withServer borrows an existing endpoint and releases its own resources afterwards. killServer retires the admitted daemon generation explicitly. Operations such as capture and renameSession are functions of this module that take the handle. |
| Common Lisp | libtmux: A connection scope with one external-operation lease.
Closing cancels owned work and leaves the tmux daemon alive. Captured data may
outlive the client. Public operations never expose its mutable storage. | |
| TypeScript | server One tmux server, addressed by the socket it listens on. | None recorded in the model |
| Rust | server A cloneable handle to one captured tmux server endpoint. | None recorded in the model |
| Go | tmux Server is an immutable handle to one tmux configuration. Its zero value is invalid. Copying a configured Server preserves its configuration and shares its mutex-guarded version cache and checked daemon identity, so a Server and the values derived from it are safe for concurrent method calls (see the package documentation). | None recorded in the model |
| Java | io Manages sessions, windows, and panes on a tmux server. | readonly |
| Clojure | libtmux Opens local resources for an explicit :socket-path or :socket-name endpoint. | Opens a closeable Java server client for an explicit endpoint. Acquisitions return persistent maps with explicit Java references for effects. |
| Kotlin | io Manages sessions, windows, and panes on a tmux server. | None recorded in the model |
| Scala | io The Java client, opaque: every member beyond java.lang.AutoCloseable#close is an extension, generated from the operation catalog or handwritten where the catalog marks it WAIT, STREAM or LIFECYCLE. Closing an owned client releases its transport, not tmux; close() comes from the AutoCloseable bound with no forwarding of its own, so Using.resource(server) { ... } works. | 2 overloads |
| F# | Lib Starts server reads and queries with the caller's cancellation token. | This F# module provides functions over the shared .NET LibTmux.Server type. |
| C++ | libtmux:: One tmux server, addressed by the socket it listens on. | None recorded in the model |
| Swift | Server A tmux server, addressed by its endpoint. | None recorded in the model |
| OCaml | Libtmux An explicit generation-bound connection. Applications retain ownership of the endpoint choice and resource lifetime. | A client is a live, generation-bound server connection. Endpoint describes a socket without connecting; closing a client releases its resources. |
| Perl | Lib Explicit tmux acquisition and commands | Construction records connection settings without tmux I/O. Optional LibTmux::Async::Server returns standard Future results for operations. |
| Raku | Lib | None recorded in the model |