Environment and processes

A process inherits a table of environment variables and a working directory from whoever started it. C# reads both through the static Environment class, reports what the runtime sees of the machine, and starts another program through System.Diagnostics.Process.

Environment variables

Environment.GetEnvironmentVariable returns null for a name that is not set. A variable can also be set to an empty string, and the two cases are different: the measured run had no greeting at all and no DOTNET_ROOT:

var greeting = Environment.GetEnvironmentVariable("GREETING") ?? "(unset)"; Console.WriteLine($"greeting {greeting}"); Console.WriteLine($"missing {Environment.GetEnvironmentVariable("NO_SUCH_VARIABLE") is null}"); Console.WriteLine($"newline {Environment.NewLine.Length}"); Console.WriteLine($"processors {Environment.ProcessorCount}"); Console.WriteLine($"64bit {Environment.Is64BitProcess}"); Console.WriteLine($"pid {Environment.ProcessId > 0}"); Console.WriteLine($"root set {Environment.GetEnvironmentVariable("DOTNET_ROOT") is not null}");

GREETING=hello dotnet run

greeting hello
missing True
newline 1
processors 4
64bit True
pid True
root set False

The variable in front of the command reached the program, which is the usual way to configure a tool without a configuration file. The line break of this system is one character, not the two of Windows, and the runtime reports four logical processors. Environment.ProcessId is the id the operating system gave this process, which a log writes to tell two runs apart. The program without the variable prints (unset) on the first line.

The machine and the process

The Environment class answers the questions a program asks about itself before it reads a configuration:

Starting another process

Process.Start starts a program, and a ProcessStartInfo with RedirectStandardOutput turns its output into a stream the parent reads. The program runs uname and echo from the system:

using System.Diagnostics; var start = new ProcessStartInfo("uname", "-m") { RedirectStandardOutput = true, }; using var process = Process.Start(start)!; var text = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); Console.WriteLine($"uname {text}"); Console.WriteLine($"status {process.ExitCode}"); var echo = new ProcessStartInfo("echo", "one two") { RedirectStandardOutput = true, }; using var second = Process.Start(echo)!; Console.WriteLine($"echo {second.StandardOutput.ReadToEnd().Trim()}"); second.WaitForExit(); Console.WriteLine($"status {second.ExitCode}");

dotnet run

uname x86_64
status 0
echo one two
status 0

The output of the child is read as text and trimmed of its line break, and the exit status of each child is 0. A child that writes a lot fills the pipe while the parent waits, so a real program reads the stream and waits at the same time, or uses BeginOutputReadLine. A command with arguments that a user supplied is passed as an argument list, never as one string to a shell, which is how a shell injection enters a program.

The working directory

Environment.CurrentDirectory is the folder the process was started in, not the folder of the assembly. A tool run from a terminal has the folder of the terminal; the same tool started by a service may have /. A program that needs a file of its own builds the path from AppContext.BaseDirectory, the folder of the assembly, and a program that needs the folder of the user takes it from an argument or a variable. The lesson on paths showed GetFullPath with an explicit base, which is the same rule.

Exercises

  1. Read a variable that is set to an empty string and compare it with a missing one.
  2. Start uname -a from the program and print its output.
  3. Print Environment.CurrentDirectory and run the same program from two folders.
  4. Start a program that does not exist and read the exception.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call reads an environment variable?

    Answer

    Environment.GetEnvironmentVariable

    The static method takes the name and returns the value or null.

  2. What does GetEnvironmentVariable return for a name that is not set?

    Answer

    null

    A missing variable is null, which the measured is null check printed True for.

  3. What does this program print? Console.WriteLine(Environment.NewLine.Length);

    Answer

    1

    A line break on this system is one character, as the measured run showed.

  4. What does Environment.ProcessorCount report?

    Answer

    The number of logical processors the process may use

    The container reported 4, which is what the scheduler offers.

  5. What does this program print? Console.WriteLine(Environment.GetEnvironmentVariable("NO_SUCH_VARIABLE") is null);

    Answer

    True

    The variable is not in the table, so the call returns null.

  6. Which class starts another program?

    Answer

    System.Diagnostics.Process

    Process.Start with a ProcessStartInfo is the API of this lesson.

  7. What does this program print? Console.WriteLine(Environment.Is64BitProcess);

    Answer

    True

    The runtime here is 64-bit, which the measured line confirmed.

  8. What does RedirectStandardOutput = true make the parent do?

    Answer

    Read the output of the child as a stream

    The child writes into a pipe that the parent reads, which is what the program did.

  9. Why should a program not rely on the current directory for its own files?

    Answer

    It is the folder the process was started in, not the folder of the assembly

    A service may start the program anywhere, so AppContext.BaseDirectory is the safe base.

  10. What does this program print? Console.WriteLine(Environment.ProcessId > 0);

    Answer

    True

    Every process has a positive id, as the measured line showed.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image