Executing .NET Core functions in a separate process

In this article, we’ll take a look at Tmds.ExecFunction , which is a library that allows developers to easily execute a .NET Core function in a separate process.

Use cases

Before we get to the code, let’s cover a few scenarios where it makes sense to execute a function as a separate process. Processes have some global state, like environment variables and the working directory. Most of the time, this global state doesn’t cause issues: When it is meaningful, libraries provide an API that allows the user to override the values. For testing, though, it’s a different story. To verify the application is properly using the global state as a default, we need to modify it. This factor is an issue because the state is shared with the test host process and the other tests running in that process. We can solve this issue by running code in a separate process that we can fully control.

The second class of use cases occurs when we want code to run with a different lifetime from the parent process. For example, suppose we want to start a process and ensure it doesn’t outlive the .NET parent (even on crashes). We could do this by putting a small process in between that monitors the parent, and kills the child when the parent has terminated. Another example is to implement double forking, which is used in script-based init managers to make sure the daemon outlives the shell that launched it. Most distributions (like Fedora and Red Hat Enterprise Linux) are now using systemd as their init manager, which doesn’t need daemons to double fork.

Everything you need to grow your career. With your free Red Hat Developer program membership, unlock our library of cheat sheets and ebooks on next-generation application development. SIGN UP

Tmds.ExecFunction

Tmds.ExecFunction is a library inspired by .NET Core’s RemoteExecutor , which is used in .NET Core’s class library for writing tests that need a separate process. This library is available on NuGet.org, so we can add it to our project using:

dotnet add package Tmds.ExecFunction

Now, let’s use it:

ExecFunction.Run(() => Console.WriteLine("Hello world!"));

We are using ExecFunction.Run and passing it a lambda that prints Hello world! That lambda is executed in a separate process. The Run method then returns when the child has terminated. ExecFunction also provides a Start method that returns a System.Diagnostics.Process and then returns immediately when the process starts. A RunAsync method is also provided, which returns a Task that completes when the process terminates.

The function we pass can have a .NET Main signature: a void / string[] argument and a void / int / Task / Task return type.

For example, we can pass some arguments:

ExecFunction.Run( (string[] args) => Console.WriteLine($"Hello {args[0]}"), new string[] { "world!" });

We can also control the environment variables, working directory, etc. by passing a configuration function:

ExecFunction.Run( () => Console.WriteLine($"HOME={Environment.GetEnvironmentVariable("HOME")}"), o => o.StartInfo.Environment["HOME"] = "/tmp");

The FunctionExecutor class makes it easy to reuse the same configuration for multiple invocations, as well. For example, we can use it as follows in xUnit tests:

private FunctionExecutor Executor = new FunctionExecutor( o => { o.StartInfo.RedirectStandardError = true; o.OnExit = p => { if (p.ExitCode != 0) { string message = $"Function execution failed with exit code: {p.ExitCode}" + Environment.NewLine + p.StandardError.ReadToEnd(); throw new Xunit.Sdk.XunitException(message); } }; }); [Fact] public void Test() { Executor.Run( () => { Assert.Equal("/tmp", Environment.GetEnvironmentVariable("HOME")); }, o => o.StartInfo.Environment["HOME"] = "/tmp" ); }

So far, we’ve been assuming you use the dotnet executable to host your application; for example, by starting xUnit tests using dotnet test . To make ExecuteFunction work from an application host (that is, you built your application into a native binary), we need to add a hook in the Main function:

static int Main(string[] args) { if (ExecFunction.IsExecFunctionCommand(args)) { return ExecFunction.Program.Main(args); } else { ExecFunction.Run(() => System.Console.WriteLine("Hello world!")); return 0; } }

Conclusion

In this article, we’ve shown how to execute .NET Core code easily in a separate process using Tmds.ExecFunction , and when doing so can be useful. Now, explore what you can make this library do.