Geekeey.Process (2.0.0)
Installation
dotnet nuget add source --name geekeey --username your_username --password your_token dotnet add package --source geekeey --version 2.0.0 Geekeey.ProcessAbout this package
.NET library for interacting with external command-line interfaces, including process execution, piping, and cancellation.
Features
- Input and Output redirection: flexible piping model, that allows to redirect the process's streams.
- Immutability: The
Commandobject is immutable, ensuring thread safely and allowing sharing of a base configuration.
Getting Started
Install the NuGet package:
dotnet add package Geekeey.Request
You may need to add our NuGet feed to your nuget.config this can be done by running the following command:
dotnet nuget add source -n geekeey https://code.geekeey.de/api/packages/geekeey/nuget/index.json
Usage
Execute a command and capturing its output:
public static async Task<int> Main()
{
var stdout = new StringBuilder();
var cmd = new Command("git").WithArguments(["config", "--get", "user.name"]) | stdout;
await cmd.ExecuteAsync();
Console.WriteLine(stdout.ToString());
return 0;
}
Execute a command and redirect its output to another command:
public static Task<int> Main()
{
var cmd = new Command("cat").WithArguments(["file.txt"]) | new Command("wc");
await cmd.ExecuteAsync();
Console.WriteLine(stdout.ToString());
}
Execute a command with cancellation support:
public static async Task<int> Main()
{
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
};
var cmd = new Command("long-running-command");
// kills the process if Ctrl+C is pressed
var app = cmd.ExecuteAsync(cts.Token);
// manually interrupt after 5 seconds
await Task.Delay(5000);
app.Interrupt();
// wait for process to exit
var result = await app;
return 0;
}
Diagnostics
The library publishes process lifecycle events through a DiagnosticListener named
Geekeey.Process. Subscribe through DiagnosticListener.AllListeners and handle the
starting, started, and finished events. Each event value is a mutable Hashtable
that is shared by the lifecycle, so values added by a listener remain available to later
stages.
| Event | Context entries available before listeners run |
|---|---|
starting |
process: the underlying System.Diagnostics.Process |
started |
All starting entries, plus startTime: DateTimeOffset |
finished |
All previous entries, plus exitTime: DateTimeOffset and exitCode: int |
At the started event, a listener may replace any redirected stream by adding a Stream
under the corresponding key: stdin, stdout, or stderr. The replacement is used by
the command instead of the process's native stream. This is useful for adapters such as
buffering, tracing, throttling, or encryption streams; the stream must support the
operations required by the consuming pipe.