Skip to content

Processes ​

Introduction ​

The Process facade runs external programs, like Laravel's: build tools, git, image converters, backups.

csharp
var result = await Process.Run("git log --oneline -5");

result.Successful();   // exit code 0
result.Failed();
result.ExitCode;
result.Output();       // standard output
result.ErrorOutput();  // standard error

Invoking Processes ​

A string runs through the shell (/bin/sh -c, or cmd /c on Windows), so pipes and && work. To pass arguments without a shell (no quoting problems with user input), give the program and the arguments separately:

csharp
await Process.Run("ls -la | grep .cs");
await Process.Run("convert", [upload, "-resize", "200x200", thumbnail]);

Throw() turns a non-zero exit code into a ProcessFailedException (with the error output):

csharp
var output = (await Process.Run("npm run build")).Throw().Output();

Process Options ​

csharp
await Process.Path("/var/www/app")      // working directory
    .Timeout(120)                        // seconds; default 60, Forever() for none
    .Env(new { NODE_ENV = "production" })
    .Input("data for stdin")
    .Run("npm run build");

A process that runs past its timeout is killed (with its child processes) and a ProcessTimedOutException is thrown. Inside a queued job, the job's own timeout stops the process too.

Process Output ​

Read output while it is produced by passing a callback; the type is "out" or "err":

csharp
await Process.Run("npm run build", (type, line) => Log.Info("{Type}: {Line}", type, line));

Asynchronous Processes ​

Start does not wait for the process:

csharp
var process = Process.Forever().Start("dotnet Blog.dll queue:work");
// When the owning application decides to stop its worker:
if (process.Running()) process.Kill();
try
{
    var result = await process.Wait();
}
catch (OperationCanceledException)
{
    // Kill cancels the wait; it does not return a successful ProcessResult.
}

Testing ​

Process.Fake() records commands instead of running them. Map command patterns (* is a wildcard) to results; other commands succeed with no output:

csharp
var processes = Process.Fake(new()
{
    ["git log*"] = Process.Result("abc123 first commit"),
    ["npm *"] = Process.Result(errorOutput: "boom", exitCode: 1),
});

await deployer.Deploy();

processes.AssertRan("git pull");
processes.AssertRan(p => p.Command == "npm run build" && p.Directory == "/var/www/app");
processes.AssertNotRan("rm -rf /");
processes.AssertRanTimes("git pull", 1);

Complete Example: Process Self-Check ​

Create this command in a Blog application:

csharp
// app/Commands/ProcessDemo.cs
using DotBlaze;
using Process = DotBlaze.Process;

namespace Blog.Commands;

public class ProcessDemo : Command
{
    public override string Signature => "demo:process";

    public override async Task<int> Handle()
    {
        var fake = Process.Fake(new()
        {
            ["dotnet --version"] = Process.Result("10.0.100\n"),
        });
        var result = await Process.Timeout(10).Run("dotnet", ["--version"]);
        if (!result.Successful() || result.Output().Trim() != "10.0.100")
            throw new InvalidOperationException("Unexpected process result.");
        fake.AssertRanTimes("dotnet --version", 1);
        Line(result.Output().Trim());
        return 0;
    }
}

Run dotblaze demo:process: the fake prints 10.0.100 without starting a child process. Remove the fake to query the actual installed SDK; then expect its installed version rather than this scripted value. Use argument arrays for variable input, Throw() when a nonzero exit should fail the caller, and handle cancellation separately from an ordinary unsuccessful exit.