diff --git a/README.md b/README.md new file mode 100644 index 0000000..085d6b7 --- /dev/null +++ b/README.md @@ -0,0 +1,110 @@ +

+ + + Proc + +

+ +

Proc

+ +

A System.Diagnostics.Process supercharger: one-liners that run a program, capture or stream its output, and stop it with Ctrl+C before killing it.

+ +

+ NuGet + CI +

+ +```csharp +var result = Proc.Start("git", "status", "--short"); // streams to the console and captures every line +``` + +```fsharp +let sha = shell { return! text $"git rev-parse HEAD" } // each {value} is always one argument +``` + +## Install + +```sh +dotnet add package Proc # C# +dotnet add package Proc.Fs # F#: shell { }, exec { } and the Cmd module +``` + +## Quick start + +```csharp +using ProcNet; + +// run a program on the shared console; throws ProcExecException on a non-zero exit code +Proc.Exec("dotnet", "--version"); + +// capture its output, while still writing it to the console as it arrives +var result = Proc.Start("git", "status", "--short"); +foreach (var line in result.ConsoleOut) + Console.WriteLine($"{(line.Error ? "err" : "out")}: {line.Line}"); + +// start a server, go on once it says it is ready, and stop it with Ctrl+C when disposed +var args = new LongRunningArguments("dotnet", "run", "--project", "api") +{ + StartedConfirmationHandler = l => l.Line.Contains("Now listening"), + SendControlCFirst = true +}; +using (var api = Proc.StartLongRunning(args, TimeSpan.FromMinutes(1))) +{ + Proc.Exec("dotnet", "test", "tests/Api.Tests"); +} +``` + +In F#, a `shell { }` block runs commands in order and stops at the first one that fails. Commands are interpolated +strings, and each `{value}` is always one argument, so values never need quoting: + +```fsharp +open Proc.Fs + +let sha = shell { + sh $"dotnet build" + let! sha = text $"git rev-parse HEAD" + for file in lines $"git ls-files | grep \.fs$" do + sh $"dotnet fantomas {file}" + return sha +} +``` + +A block can also start a background process and stop it at the end of a scope, run clean-up commands, and run blocks +at the same time: + +```fsharp +shell { + use! api = background (sh $"dotnet run --project api" |> Cmd.waitFor (fun l -> l.Contains "Now listening")) + use! _ = defer (sh $"docker compose down") + let! _ = concurrently [ steps { sh $"dotnet test tests/A" }; steps { sh $"dotnet test tests/B" } ] + return () +} +``` + +## What it does + +- `Proc.Exec()` for the quick one-liners, `Proc.ExecAsync()` for the same with a `CancellationToken`. +- `Proc.Start()` captures the console output as well as printing it in real time, and lets you script standard input. +- `Proc.StartLongRunning()` starts a server or database and returns once it prints that it is ready. +- `ObservableProcess` and `EventBasedObservableProcess` wrap `System.Diagnostics.Process` as an `IObservable`. + `ObservableProcess` listens on the output buffers directly, so it sees prompts that never end in a newline. +- `SendControlCFirst = true` sends `SIGINT` before falling back to a hard `SIGKILL` (`Process.Kill()`), so a process + can shut down cleanly. +- On .NET 11 it uses the new Process APIs: in-process `SIGINT` on Linux and macOS, `KillOnParentExit` and + `InheritedHandles`. + +## Packages + +| Package | What it is | | +|---|---|---| +| [`Proc`](src/Proc/README.md) | the C# API: `Proc.Exec`, `Proc.Start`, `Proc.StartLongRunning` and the observable processes | [![NuGet](https://img.shields.io/nuget/v/Proc?style=flat-square)](https://www.nuget.org/packages/Proc) | +| [`Proc.Fs`](src/Proc.Fs/README.md) | F# bindings: `shell { }`, `exec { }`, the `Cmd` module and pipes | [![NuGet](https://img.shields.io/nuget/v/Proc.Fs?style=flat-square)](https://www.nuget.org/packages/Proc.Fs) | + +## Learn more + +- [Proc reference](src/Proc/README.md): every call and option, `SIGINT` handling, line boundaries and .NET 11 +- [Proc.Fs reference](src/Proc.Fs/README.md): `shell { }`, background processes, `sh` quoting rules, `Cmd`, pipes and `exec { }` +- [Releases](https://github.com/nullean/proc/releases) +- [Contributing](https://github.com/nullean/.github/blob/main/CONTRIBUTING.md) + +MIT licensed. Copyright Nullean and contributors. diff --git a/readme.md b/readme.md deleted file mode 100644 index 530c26d..0000000 --- a/readme.md +++ /dev/null @@ -1,243 +0,0 @@ -# Proc - - - - - -A dependency free `System.Diagnostics.Process` supercharger. - -1. `Proc.Exec()` for the quick one-liners -2. `Proc.Start()` for the quick one-liners - - Use if you want to capture the console output as well as print these message in real time. - - Proc.Start() also allows you to script StandardIn and react to messages -3. Wraps `System.Diagnostics.Process` as an `IObservable` - * `ProcessObservable` stream based wrapper - * `EventBasedObservableProcess` event based wrapper -4. Built in support to send `SIGINT` to any process before doing a hard `SIGKILL` (`Process.Kill()`) - * Has to be set using `SendControlCFirst = true` on `StartArguments` - -## Proc.Exec - -Execute a process and blocks using a default timeout of 4 minutes. This method uses the same console session -as and as such will print the binaries console output. Throws a `ProcExecException` if the command fails to execute. -See also `ExecArguments` for more options - -```csharp -Proc.Exec("ipconfig", "/all"); -``` - -## Proc.Start - -start a process and block using the default timeout of 4 minutes -```csharp -var result = Proc.Start("ipconfig", "/all"); -``` - -Provide a custom timeout and an `IConsoleOutWriter` that can output to console -while this line is blocking. The following example writes `stderr` in red. - -```csharp -var result = Proc.Start("ipconfig", TimeSpan.FromSeconds(10), new ConsoleOutColorWriter()); -``` - -More options can be passed by passing `StartArguments` instead to control how the process should start. - -```csharp -var args = new StartArguments("ipconfig", "/all") -{ - WorkingDirectory = .. -} -Proc.Start(args, TimeSpan.FromSeconds(10)); -``` - -The static `Proc.Start` has a timeout of `4 minutes` if not specified. - -`result` has the following properties - -* `Completed` true if the program completed before the timeout -* `ConsoleOut` a list the console out message as `LineOut` - instances where `Error` on each indicating whether it was written on `stderr` or not -* `ExitCode` - -**NOTE** `ConsoleOut` will always be set regardless of whether an `IConsoleOutWriter` is provided - -## Proc.StartLongRunning - -Start a process that keeps running, such as a web server or a database, and go on once it says it is ready. -Disposing the returned subscription stops the process. - -```csharp -var args = new LongRunningArguments("dotnet", "run", "--project", "api") -{ - StartedConfirmationHandler = l => l.Line.Contains("Now listening"), - SendControlCFirst = true -}; -using (var api = Proc.StartLongRunning(args, TimeSpan.FromMinutes(1))) -{ - // api.ProcessId, api.ExitCode (once it exited on its own), api.WaitForCompletion(timeout) -} -``` - -`StartLongRunning` waits for a line that `StartedConfirmationHandler` accepts. Without a handler it returns straight away. -When no such line comes in time, it stops the process and throws `ProcExecException`. -`ExitCode` stays `null` while the process runs, and after disposing stopped it. - -## ObservableProcess - -The heart of it all this is an `IObservable`. It listens on the output buffers directly and does not wait on -newlines to emit. - -To create an observable process manually follow the following pattern: - -```csharp -using (var p = new ObservableProcess(args)) -{ - p.Subscribe(c => Console.Write(c.Characters)); - p.WaitForCompletion(TimeSpan.FromSeconds(2)); -} -``` - -The observable is `cold` untill subscribed and is not intended to be reused or subscribed to multiple times. If you need to -share a subscription look into RX's `Publish`. - -The `WaitForCompletion()` call blocks so that `p` is not disposed which would attempt to shutdown the started process. - -The default for doing a shutdown is through `Process.Kill` this is a hard `SIGKILL` on the process. - -The cool thing about `Proc` is that it supports `SIGINT` interoptions as well to allow for processes to be cleanly shutdown. - -```csharp -var args = new StartArguments("elasticsearch.bat") -{ - SendControlCFirst = true -}; -``` - -This will attempt to send a `Control+C` into the running process console on windows first before falling back to `Process.Kill`. -On Linux and macOS this shells out to `kill -SIGINT`, unless running on .NET 11+ (see below), where it delivers the signal -in-process instead. - - -Dealing with `byte[]` characters might not be what you want to program against, so `ObservableProcess` allows the following as well. - - -```csharp -using (var p = new ObservableProcess(args)) -{ - p.SubscribeLines(c => Console.WriteLine(c.Line)); - p.WaitForCompletion(TimeSpan.FromSeconds(2)); -} -``` - -Instead of proxying `byte[]` as they are received on the socket this buffers and only emits on lines. - -In some cases it can be very useful to introduce your own word boundaries - -```csharp -public class MyProcObservable : ObservableProcess -{ - public MyProcObservable(string binary, params string[] arguments) : base(binary, arguments) { } - - public MyProcObservable(StartArguments startArguments) : base(startArguments) { } - - protected override bool BufferBoundary(char[] stdOut, char[] stdErr) - { - return base.BufferBoundary(stdOut, stdErr); - } -} -``` - -returning true inside `BufferBoundary` will yield the line to `SubscribeLine()`. This could be usefull e.g if your process -prompts without a new line: - -> Continue [Y/N]: - -A more concrete example of this is when you call a `bat` file on windows and send a `SIGINT` signal it will *always* prompt: - -> Terminate batch job (Y/N)? - -Which would not yield to `SubscribeLines` and block any waithandles unnecessary. `ObservableProcess` handles this edgecase -therefor OOTB and automatically replies with `Y` on `stdin` in this case. - -Also note that `ObservableProcess` will yield whatever is in the buffer before OnCompleted(). - - -# EventBasedObservable - -`ObservableProcess`'s sibbling that utilizes `OutputDataReceived` and `ErrorDataReceived` and can only emit lines. - -On .NET 11+ this reads through [`Process.ReadAllLinesAsync`](https://devblogs.microsoft.com/dotnet/process-api-improvements-in-dotnet-11/) -instead, which multiplexes `stdout`/`stderr` on a single thread without blocking any thread pool threads. - -# F# bindings - -The `Proc.Fs` package wraps Proc for F#. A `shell { }` block runs commands in order and stops at the first one that fails. -Commands are interpolated strings, and each `{value}` is always one argument, so values never need quoting. - -```fsharp -open Proc.Fs - -let sha = shell { - sh $"dotnet build" - let! sha = text $"git rev-parse HEAD" - for file in lines $"git ls-files | grep \.fs$" do - sh $"dotnet fantomas {file}" - return sha -} -``` - -A block can also start a background process and stop it at the end of a scope, run clean-up commands, and run blocks -at the same time: - -```fsharp -shell { - use! api = background (sh $"dotnet run --project api" |> Cmd.waitFor (fun l -> l.Contains "Now listening")) - use! _ = defer (sh $"docker compose down") - let! _ = concurrently [ steps { sh $"dotnet test tests/A" }; steps { sh $"dotnet test tests/B" } ] - return () -} -``` - -See [src/Proc.Fs/README.md](src/Proc.Fs/README.md) for `shell { }`, background processes, the `Cmd` module, pipes and -the `exec { }` builder. - -# .NET 11 - -`Proc` targets `net11.0` alongside its other target frameworks and picks up a few of the -[Process API improvements shipped in .NET 11](https://devblogs.microsoft.com/dotnet/process-api-improvements-in-dotnet-11/) -when running on that TFM. These are all opt-in/no-op elsewhere, so there's nothing to change if you stay on an older TFM. - -* `SendControlC`/`SendControlCFirst` deliver `SIGINT` on Linux/macOS via `SafeProcessHandle.Signal` instead of shelling out - to the `kill` binary. -* `EventBasedObservableProcess` reads through `Process.ReadAllLinesAsync` (see above). -* `Proc.Exec` without a `Timeout` calls `Process.Run` directly, and `Proc.ExecAsync` without a `Timeout` and with a - token that cannot be cancelled calls `Process.RunAsync` directly. With a timeout or a cancellable token both keep - using Proc's own wait loop: on timeout or cancellation `Process.Run`/`RunAsync` kill only the started process, - whereas Proc kills its entire process tree and throws. -* Two new options on `StartArguments`/`ExecArguments`, both no-ops on older TFMs or unsupported platforms: - -```csharp -var args = new StartArguments("some-long-running-tool") -{ - // Kills the started process if this process exits, including crashes. Backed by Job objects on Windows - // and PR_SET_PDEATHSIG on Linux. Only takes effect on .NET 11+ on Windows or Linux. - KillOnParentExit = true, - - // Restricts which handles the started process inherits, instead of every inheritable handle from this - // process. Only takes effect on .NET 11+. - InheritedHandles = new List() -}; -``` - - - - - - - - - - - - diff --git a/src/Proc.Fs/README.md b/src/Proc.Fs/README.md index 15fd5e3..564250e 100644 --- a/src/Proc.Fs/README.md +++ b/src/Proc.Fs/README.md @@ -1,12 +1,40 @@ # Proc.Fs -F# bindings for Proc. +![Proc](https://raw.githubusercontent.com/nullean/nullean.github.io/main/assets/nullean-mark-128.png) -Proc is a library that turns `System.Diagnostics.Process` into a stream based `IObservable` capable of capturing a process's true output while still emitting line based events. +F# bindings for Proc: run commands the way a shell script does, with every interpolated value passed as exactly one +argument, so values never need quoting. -The library ships with two computation expression builders, `shell { }` and `exec { }`, and a `Cmd` module for running commands with `|>`. It targets .NET 10 and .NET 11. +[![NuGet](https://img.shields.io/nuget/v/Proc.Fs?style=flat-square)](https://www.nuget.org/packages/Proc.Fs) -# Shell +[Proc](https://www.nuget.org/packages/Proc) turns `System.Diagnostics.Process` into a stream based `IObservable` +capable of capturing a process's true output while still emitting line based events. This package ships two +computation expression builders, `shell { }` and `exec { }`, and a `Cmd` module for running commands with `|>`. +It targets .NET 10 and .NET 11. + +## Install + +```sh +dotnet add package Proc.Fs +``` + +## Quick start + +```fsharp +open Proc.Fs + +let sha = shell { + sh $"dotnet build" + let! sha = text $"git rev-parse HEAD" + for file in lines $"git ls-files | grep \.fs$" do + sh $"dotnet fantomas {file}" + return sha +} +``` + +The first command that fails throws a `ProcExecException` and stops the block. + +## Shell `shell { }` runs commands one after the other, the way a shell script does. The first command that fails throws a `ProcExecException` and stops the block. @@ -70,7 +98,7 @@ shell { A command's own `Cmd.cwd` resolves against the shell's directory, and its own `Cmd.env` wins over `setEnv`. `do!` still works in front of commands and steps, for example `do! cd "src"`. -## Background processes, clean-up and running steps at the same time +### Background processes, clean-up and running steps at the same time ```fsharp shell { @@ -121,7 +149,7 @@ failure of the deferred command goes to standard error. - A background process the block started that fails also fails the branches. - Output of the branches interleaves line by line on the console. -## Writing commands with `sh` +### Writing commands with `sh` `sh` takes an interpolated string, `$"…"`. It splits **only the text you wrote**: @@ -160,7 +188,7 @@ sh $""" Use `$$"""…"""` when the command contains literal braces; its placeholders are `{{value}}`. A plain string without `$` does not compile. `Cmd.ofString` parses text that only exists at runtime. -# Cmd +## Cmd `cmd binary arguments` builds a command without running it. The `Cmd` module adjusts and runs it, and reads well with `|>`. @@ -198,7 +226,7 @@ cmd "dotnet" ["test"] |> Cmd.iter (fun line -> if line.Contains "Failed" then pr `Cmd.validExitCode` decides which exit codes count as success; the default is only `0`. -## Files, failures and retries +### Files, failures and retries | Function | Does | Like | |---|---|---| @@ -225,7 +253,7 @@ Relative file names resolve against the working directory of the command, so ins Standard error stays on the console. A capture such as `Cmd.lines` reads nothing from a command whose standard out goes to a file. `Cmd.iter` passes lines on again when a retried command runs again. -## Pipes +### Pipes `|>|` streams the standard out of one command into the standard input of the next, like `|` in a shell: @@ -247,7 +275,7 @@ let sorted = cmd "sort" [] |> Cmd.stdin ["b"; "a"] |> Cmd.lines |> Cmd.get A command without `Cmd.stdin` or a pipe gets its standard input closed straight away. -# Exec +## Exec A `CE` to make it **REAL** easy to execute processes. @@ -283,7 +311,7 @@ exec { env Map[("key", "value")] working_dir "." send_control_c false - timeout (TimeSpan.FromSeconds(10)) + timeout (TimeSpan.FromSeconds 10.) kill_on_parent_exit true filter_output (fun l -> l.Line.Contains "clean") valid_exit_code (fun i -> i <> 0) @@ -362,7 +390,7 @@ returns the exit code and the full console output. ```fsharp -let process = exec { +let running = exec { binary "dotnet" arguments "--help" wait_until (fun l -> l.Line.Contains "clean") @@ -372,7 +400,7 @@ let process = exec { returns an already running process but only after it confirms a line was printed ```fsharp -let process = exec { +let running = exec { binary "dotnet" arguments "--help" wait_until_and_disconnect (fun l -> l.Line.Contains "clean") @@ -380,3 +408,9 @@ let process = exec { ``` returns an already running process but only after it confirms a line was printed. This version will stop the yielding standard/out lines which may utilize memory consumption which is no longer needed. + +## Learn more + +- The C# API underneath: [Proc](https://www.nuget.org/packages/Proc) +- Source and issues: https://github.com/nullean/proc +- [Releases](https://github.com/nullean/proc/releases) diff --git a/src/Proc/README.md b/src/Proc/README.md index 0f7f061..969323b 100644 --- a/src/Proc/README.md +++ b/src/Proc/README.md @@ -1,61 +1,105 @@ # Proc -A dependency free `System.Diagnostics.Process` supercharger. - -1. `Proc.Exec()` for the quick one-liners -2. `Proc.Start()` for the quick one-liners - - Use if you want to capture the console output as well as print these message in real time. - - Proc.Start() also allows you to script StandardIn and react to messages -3. Wraps `System.Diagnostics.Process` as an `IObservable` - * `ProcessObservable` stream based wrapper - * `EventBasedObservableProcess` event based wrapper -4. Built in support to send `SIGINT` to any process before doing a hard `SIGKILL` (`Process.Kill()`) - * Has to be set using `SendControlCFirst = true` on `StartArguments` - +![Proc](https://raw.githubusercontent.com/nullean/nullean.github.io/main/assets/nullean-mark-128.png) + +A `System.Diagnostics.Process` supercharger: one-liners that run a program, capture or stream its output, and stop it +with Ctrl+C before killing it. + +[![NuGet](https://img.shields.io/nuget/v/Proc?style=flat-square)](https://www.nuget.org/packages/Proc) + +## Install + +```sh +dotnet add package Proc +``` + +## Quick start + +```csharp +using ProcNet; + +// run a program on the shared console; throws ProcExecException on a non-zero exit code +Proc.Exec("dotnet", "--version"); + +// capture its output, while still writing it to the console as it arrives +var result = Proc.Start("git", "status", "--short"); +foreach (var line in result.ConsoleOut) + Console.WriteLine($"{(line.Error ? "err" : "out")}: {line.Line}"); +Console.WriteLine($"exit code {result.ExitCode}"); +``` + +Proc does four things: + +1. `Proc.Exec()` for the quick one-liners. +2. `Proc.Start()` when you want to capture the console output as well as print it in real time. + It also lets you script standard input and react to messages. +3. It wraps `System.Diagnostics.Process` as an `IObservable`: + - `ObservableProcess`, a stream based wrapper; + - `EventBasedObservableProcess`, an event based wrapper. +4. It can send `SIGINT` to a process before falling back to a hard `SIGKILL` (`Process.Kill()`). + Set `SendControlCFirst = true` on `StartArguments` to opt in. + +Pick the call by what you need back: + +| Need | Call | Returns | +|---|---|---| +| run it, fail on a non-zero exit | `Proc.Exec("dotnet", "build")` | exit code; throws `ProcExecException` otherwise | +| the same, async | `await Proc.ExecAsync(new ExecArguments("dotnet", "build"), ct)` | exit code | +| its output | `Proc.Start("git", "status", "--short")` | `ProcessCaptureResult`: `Completed`, `ExitCode`, `ConsoleOut` | +| each line as it arrives | `Proc.StartRedirected(handler, "dotnet", "test")` | `ProcessResult` | +| a long-running server you wait on | `Proc.StartLongRunning(args, waitForStartedConfirmation)` | a subscription with `ProcessId` and `ExitCode`; dispose it to stop | + +Pass every argument separately, `Proc.Exec("git", "commit", "-m", message)`, never one string with spaces: each one +reaches the process unchanged. There is no default timeout: without `Timeout` a call waits for the process to exit. + ## Proc.Exec -Execute a process and blocks using a default timeout of 4 minutes. This method uses the same console session -as and as such will print the binaries console output. Throws a `ProcExecException` if the command fails to execute. -See also `ExecArguments` for more options +Executes a process and blocks until it exits. It uses the same console session as your program, so the program's +output goes straight to the console. Throws a `ProcExecException` when the program fails to start, exits with an exit +code that `ValidExitCodeClassifier` does not accept (by default anything but `0`), or runs past its `Timeout`. +See `ExecArguments` for more options. ```csharp Proc.Exec("ipconfig", "/all"); ``` -## Proc.Start - -start a process and block using the default timeout of 4 minutes ```csharp -var result = Proc.Start("ipconfig", "/all"); +Proc.Exec(new ExecArguments("npm", "ci") +{ + WorkingDirectory = "web", + Environment = new Dictionary { ["CI"] = "true" }, // a null value removes a variable + Timeout = TimeSpan.FromMinutes(5), // kills the whole process tree, then throws + ValidExitCodeClassifier = code => code is 0 or 2 +}); ``` -Provide a custom timeout and an `IConsoleOutWriter` that can output to console -while this line is blocking. The following example writes `stderr` in red. +## Proc.Start + +Starts a process and blocks until it exits, capturing its output. ```csharp -var result = Proc.Start("ipconfig", TimeSpan.FromSeconds(10), new ConsoleOutColorWriter()); +var result = Proc.Start("ipconfig", "/all"); ``` -More options can be passed by passing `StartArguments` instead to control how the process should start. +Pass `StartArguments` to control how the process starts, for instance with a timeout and an `IConsoleOutWriter` that +writes to the console while the call blocks. `ConsoleOutColorWriter`, the default, writes `stderr` in red. ```csharp -var args = new StartArguments("ipconfig", "/all") +var result = Proc.Start(new StartArguments("ipconfig", "/all") { - WorkingDirectory = .. -} -Proc.Start(args, TimeSpan.FromSeconds(10)); + WorkingDirectory = "..", + Timeout = TimeSpan.FromSeconds(10), + ConsoleOutWriter = new ConsoleOutColorWriter() +}); ``` -The static `Proc.Start` has a timeout of `4 minutes` if not specified. - -`result` has the following properties +`Proc.Start` does not throw on a non-zero exit code. `result` has these properties: -* `Completed` true if the program completed before the timeout -* `ConsoleOut` a list the console out message as `LineOut` - instances where `Error` on each indicating whether it was written on `stderr` or not -* `ExitCode` +- `Completed`: true if the program completed before the timeout. +- `ConsoleOut`: the console output as a list of `LineOut`, where `Error` says whether a line was written on `stderr`. +- `ExitCode`. -**NOTE** `ConsoleOut` will always be set regardless of whether an `IConsoleOutWriter` is provided +`ConsoleOut` is always set, whether or not an `IConsoleOutWriter` is provided. ## Proc.StartLongRunning @@ -80,12 +124,13 @@ When no such line comes in time, it stops the process and throws `ProcExecExcept ## ObservableProcess -The heart of it all this is an `IObservable`. It listens on the output buffers directly and does not wait on +The heart of it all is an `IObservable`. It listens on the output buffers directly and does not wait on newlines to emit. -To create an observable process manually follow the following pattern: +To create an observable process manually, follow this pattern: ```csharp +var args = new StartArguments("dotnet", "--info"); using (var p = new ObservableProcess(args)) { p.Subscribe(c => Console.Write(c.Characters)); @@ -93,14 +138,13 @@ using (var p = new ObservableProcess(args)) } ``` -The observable is `cold` untill subscribed and is not intended to be reused or subscribed to multiple times. If you need to -share a subscription look into RX's `Publish`. +The observable is cold until subscribed, and is not meant to be reused or subscribed to more than once. To share a +subscription, look into Rx's `Publish`. -The `WaitForCompletion()` call blocks so that `p` is not disposed which would attempt to shutdown the started process. +The `WaitForCompletion()` call blocks so that `p` is not disposed, which would shut down the started process. -The default for doing a shutdown is through `Process.Kill` this is a hard `SIGKILL` on the process. - -The cool thing about `Proc` is that it supports `SIGINT` interoptions as well to allow for processes to be cleanly shutdown. +By default a shutdown goes through `Process.Kill`, a hard `SIGKILL` on the process. Proc also supports `SIGINT`, so a +process can shut down cleanly: ```csharp var args = new StartArguments("elasticsearch.bat") @@ -109,12 +153,11 @@ var args = new StartArguments("elasticsearch.bat") }; ``` -This will attempt to send a `Control+C` into the running process console on windows first before falling back to `Process.Kill`. -Linux and OSX support for this flag is still in the works so thats why this behaviour is opt in. - - -Dealing with `byte[]` characters might not be what you want to program against, so `ObservableProcess` allows the following as well. +This sends a Ctrl+C into the running process's console first, then falls back to `Process.Kill`. On Windows Proc +delivers it through a small helper program it ships. On Linux and macOS it shells out to `kill -SIGINT`, unless running +on .NET 11+ (see below), where it delivers the signal in-process instead. +Dealing with `char[]` buffers might not be what you want to program against, so `ObservableProcess` also emits lines: ```csharp using (var p = new ObservableProcess(args)) @@ -124,9 +167,9 @@ using (var p = new ObservableProcess(args)) } ``` -Instead of proxying `byte[]` as they are received on the socket this buffers and only emits on lines. +Instead of passing on the buffers as they are received, this buffers and only emits whole lines. -In some cases it can be very useful to introduce your own word boundaries +In some cases it is useful to introduce your own line boundaries: ```csharp public class MyProcObservable : ObservableProcess @@ -142,36 +185,59 @@ public class MyProcObservable : ObservableProcess } ``` -returning true inside `BufferBoundary` will yield the line to `SubscribeLine()`. This could be usefull e.g if your process +Returning true from `BufferBoundary` yields the buffered text to `SubscribeLines()`. This is useful when your process prompts without a new line: > Continue [Y/N]: -A more concrete example of this is when you call a `bat` file on windows and send a `SIGINT` signal it will *always* prompt: +A more concrete example: a `bat` file on Windows that gets a `SIGINT` *always* prompts > Terminate batch job (Y/N)? -Which would not yield to `SubscribeLines` and block any waithandles unnecessary. `ObservableProcess` handles this edgecase -therefor OOTB and automatically replies with `Y` on `stdin` in this case. - -Also note that `ObservableProcess` will yield whatever is in the buffer before OnCompleted(). - - -# EventBasedObservable - -`ObservableProcess`'s sibbling that utilizes `OutputDataReceived` and `ErrorDataReceived` and can only emit lines. - - - - +which would not yield to `SubscribeLines` and would block wait handles unnecessarily. `ObservableProcess` handles this +case out of the box and replies with `Y` on `stdin`. +`ObservableProcess` also yields whatever is left in the buffer before `OnCompleted()`. +## EventBasedObservableProcess +The sibling of `ObservableProcess` that uses `OutputDataReceived` and `ErrorDataReceived`, and so can only emit lines. +On .NET 11+ it reads through [`Process.ReadAllLinesAsync`](https://devblogs.microsoft.com/dotnet/process-api-improvements-in-dotnet-11/) +instead, which multiplexes `stdout` and `stderr` on a single thread without blocking any thread pool threads. +## .NET 11 +Proc targets `net11.0` alongside its other target frameworks, and picks up a few of the +[Process API improvements shipped in .NET 11](https://devblogs.microsoft.com/dotnet/process-api-improvements-in-dotnet-11/) +when running on it. They are opt-in or no-ops elsewhere, so there is nothing to change if you stay on an older target +framework. +- `SendControlC` and `SendControlCFirst` deliver `SIGINT` on Linux and macOS through `SafeProcessHandle.Signal` + instead of shelling out to the `kill` binary. +- `EventBasedObservableProcess` reads through `Process.ReadAllLinesAsync` (see above). +- `Proc.Exec` without a `Timeout` calls `Process.Run` directly, and `Proc.ExecAsync` without a `Timeout` and with a + token that cannot be cancelled calls `Process.RunAsync` directly. With a timeout or a cancellable token both keep + using Proc's own wait loop: on timeout or cancellation `Process.Run` and `RunAsync` kill only the started process, + whereas Proc kills its entire process tree and throws. +- Two new options on `StartArguments` and `ExecArguments`, both no-ops on older target frameworks or unsupported + platforms: +```csharp +var args = new StartArguments("some-long-running-tool") +{ + // Kills the started process if this process exits, including crashes. Backed by Job objects on Windows + // and PR_SET_PDEATHSIG on Linux. Only takes effect on .NET 11+ on Windows or Linux. + KillOnParentExit = true, + // Restricts which handles the started process inherits, instead of every inheritable handle from this + // process. Only takes effect on .NET 11+. + InheritedHandles = new List() +}; +``` +## Learn more +- F# bindings: [Proc.Fs](https://www.nuget.org/packages/Proc.Fs), with `shell { }`, `exec { }` and the `Cmd` module +- Source and issues: https://github.com/nullean/proc +- [Releases](https://github.com/nullean/proc/releases)