Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 132 ยท Standard Library Tour

Environment, Processes and Signals

Use environment variables, command-line arguments, exit codes and child processes in Rust, understand why env::set_var is unsafe in 2024, and handle Unix signals.

A program does not live alone. It starts with arguments from whoever launched it, inherits environment variables (PATH, HOME, PORT, DATABASE_URL), can start other programs and read their output, ends with an exit code that scripts and CI systems act on, and may be interrupted by signals such as Ctrl+C. The standard library covers all of this in std::env, std::process and (for the parts that are specific to Unix) std::os::unix.

This lesson shows each of them, with one eye on safety and testing. Reading the environment is easy; doing it well means converting once at the edge of your program and passing plain values inward. Spawning processes is easy to get subtly wrong (shell injection, forgotten wait, deadlocked pipes). And in the 2024 edition one function that looks harmless, env::set_var, became unsafe, for a good reason you will see below.

Our editor runs your program in a locked-down sandbox: no network, a scratch folder, and no promise that any external program (ls, git, curl) exists. The runnable examples therefore avoid depending on the machine. Where a feature needs a real shell, a real terminal or a real second program, the code is shown read-only and labelled as such.

Command-line arguments

std::env::args() is an iterator over the arguments as Strings. The first item is the program name (or path), and the real arguments start at the second. It panics if an argument is not valid Unicode; args_os() yields OsStrings and never panics.

Rust Reading the arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In the editor you pass no arguments, so the list is empty. On your computer you would run cargo run -- hello 42 (everything after -- goes to your program) or ./myprogram hello 42. To keep the parsing logic testable, put it in a function that takes the arguments as a parameter instead of calling env::args() inside:

Rust A small argument parser you can test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This parser handles a few conventions by hand. For anything real, use the clap crate, which generates parsing, --help text, validation and shell completion from a struct (read-only, needs clap = { version = "4", features = ["derive"] }):

Rust
// read-only: needs the clap crate
use clap::Parser;

/// Counts words in files.
#[derive(Parser)]
struct Cli {
    /// Print more detail
    #[arg(short, long)]
    verbose: bool,

    /// Files to read
    files: Vec<std::path::PathBuf>,
}

fn main() {
    let cli = Cli::parse(); // exits with a helpful message on bad input
    println!("{} file(s), verbose = {}", cli.files.len(), cli.verbose);
}

Environment variables

env::var("NAME") returns Result<String, VarError>. VarError::NotPresent means unset, and VarError::NotUnicode means the value exists but is not valid UTF-8; var_os returns an Option<OsString> for the latter case. Remember that an environment variable that is set but empty is Ok(""), which is not the same as unset.

Rust Reading environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

env::consts::OS is decided at compile time, so on your Windows laptop it says windows.

Setting variables: why it is unsafe in 2024

On Unix, the process environment is one global table shared by all threads, and the C library offers no thread-safe way to modify it while other threads read it (getenv returns a pointer into the table, and setenv may free or move it). A Rust program that calls set_var in one thread while any other thread, or C code such as a DNS resolver, reads the environment, can crash. Because the compiler cannot check that, env::set_var and env::remove_var are unsafe in the 2024 edition:

Rust set_var needs an unsafe block (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error[E0133]: call to unsafe function set_var is unsafe and requires unsafe block, and a note to consult the function's documentation about how to avoid undefined behavior (the documentation explains the thread problem described above). The unsafe block is a promise that nothing else is touching the environment at that moment. It is legitimate at the very start of main, before any thread exists:

Rust Setting a variable before any thread starts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The better design is to avoid mutating the global environment at all. Read the settings once, put them in a plain struct, and pass it around. To test that code, pass a lookup function instead of reading env::var directly, so a test can supply fake values and tests running in parallel never fight over global state:

Rust Configuration with an injectable lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

For .env files during development, the dotenvy crate loads them into the environment at startup (read-only: dotenvy::dotenv().ok(); as the first line of main).

Exit codes

Every process ends with an integer exit status. By convention 0 means success and anything else means failure. Shells expose it as $?, && and || branch on it, and CI systems fail a job on non-zero. The previous lesson on main and exit codes covers returning Result or ExitCode from main. Here is the third way, std::process::exit, which ends the process immediately:

Rust process::exit skips destructors (exit code 3)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You see cleanup for b but never cleanup for a. exit is for the rare case when you have decided to stop right now; prefer returning an ExitCode from main so that destructors run. process::abort() is even harsher: it kills the process with a signal (usually SIGABRT) and a core dump.

Running other programs with Command

std::process::Command is a builder: you describe the program, its arguments, environment and working directory, and then run it with status(), output() or spawn(). Describing a command costs nothing and does not start anything, so we can inspect a builder safely:

Rust Describing a command without running it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that each argument is passed as a separate item. Command does not use a shell: Command::new("ls").arg("-l; rm -rf /") passes the literal text -l; rm -rf / as one argument to ls, so there is no shell injection. That is the main safety advantage over building a string and running it through sh -c. Only use a shell on purpose (Command::new("sh").arg("-c").arg(script)), and never put untrusted input into the script text.

Running and capturing output (read-only)

These snippets need real programs on your machine, so they are read-only. The three ways to run a command differ in what they do with the child's standard streams:

Rust
// read-only: needs `git` installed
use std::process::Command;

fn main() -> std::io::Result<()> {
    // status(): run, wait, inherit stdin/stdout/stderr (the child prints directly to your terminal).
    let status = Command::new("git").arg("--version").status()?;
    println!("exit status: {status}, success: {}", status.success());

    // output(): run, wait, capture stdout and stderr completely.
    let output = Command::new("git").args(["rev-parse", "--short", "HEAD"]).output()?;
    if output.status.success() {
        let commit = String::from_utf8_lossy(&output.stdout);
        println!("HEAD is {}", commit.trim());
    } else {
        eprintln!("git failed: {}", String::from_utf8_lossy(&output.stderr));
    }
    Ok(())
}

Check the status. output() returns Ok whenever the program could be started, even if it then failed with exit code 1; the failure is in output.status. status.code() is Some(n) for a normal exit and None when a signal killed the child (on Unix, use std::os::unix::process::ExitStatusExt; and status.signal() tells you which).

For more control, spawn() returns a Child that runs alongside your program, with pipes you can read and write. This sends text to the sort program and reads the sorted result:

Rust
// read-only: needs the `sort` program (Linux/macOS)
use std::io::Write;
use std::process::{Command, Stdio};

fn main() -> std::io::Result<()> {
    let mut child = Command::new("sort")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;

    // take() moves the pipe out of the child; dropping it closes it, which tells `sort` the input is over.
    let mut stdin = child.stdin.take().expect("stdin was piped");
    stdin.write_all(b"pear\napple\nfig\n")?;
    drop(stdin);

    let output = child.wait_with_output()?; // waits for exit and reads all output
    println!("{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}

Three classic mistakes with child processes:

  • Forgetting to close the child's stdin. The child waits for more input forever, and so do you. Drop the handle.
  • Deadlock with full pipes. If a child writes more than the pipe buffer (about 64 KB) to a pipe you are not reading, it blocks. Use wait_with_output() or read the pipes from separate threads.
  • Zombie processes. A child that has exited but was never waited for stays in the process table. Always call wait(), status() or output(). Dropping a Child does not kill or wait for it.

Signals

A signal is a small asynchronous message from the operating system or another process: SIGINT (Ctrl+C), SIGTERM (polite "please stop", sent by kill and by container runtimes), SIGHUP, SIGUSR1, SIGKILL (cannot be caught). The Rust standard library has no API to receive signals; it only lets you send one to a child (Child::kill, which sends SIGKILL). By default Ctrl+C kills your program at once, without running destructors, so a server that wants a graceful shutdown must install a handler. In real projects you use a crate (read-only):

Rust
// read-only: needs the ctrlc crate (ctrlc = "3")
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

fn main() {
    let stop = Arc::new(AtomicBool::new(false));
    let flag = Arc::clone(&stop);
    ctrlc::set_handler(move || flag.store(true, Ordering::SeqCst)).expect("handler");

    while !stop.load(Ordering::SeqCst) {
        // ... do a unit of work ...
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    println!("shutting down cleanly");
}

In an async server you would use tokio::signal::ctrl_c() or tokio::signal::unix::signal(SignalKind::terminate()). The crates signal-hook and nix cover the full Unix feature set.

To see what is going on underneath, the next example installs a handler by calling the C library directly, as in the FFI lesson, and then sends the program a signal to itself with raise. The handler may do almost nothing: it runs in the middle of whatever your thread was doing, and only async-signal-safe operations are allowed (no allocation, no println!, no locks). Setting an atomic flag is the standard safe move.

Rust A signal handler that sets a flag (Linux)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is exactly the pattern behind the ctrlc crate: the handler sets a flag and the main loop checks it between units of work. Windows has no POSIX signals (it has console control events), another reason to use a cross-platform crate in real programs.

Putting it together

A well-behaved command-line tool usually follows the same outline:

  1. Parse arguments (clap) and read the environment once, into a config struct.
  2. Do the work in functions that take plain values and return Result.
  3. In main, turn the result into an exit code: 0 for success, 1 for a general failure, 2 for bad usage (a common convention), and print errors to stderr (eprintln!), data to stdout.
  4. Install a signal handler if the program runs for a long time, and shut down cleanly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the first item of std::env::args()?

    args() starts with the program name. Use .skip(1) to get the arguments the user passed.
  2. 2. Why is env::set_var unsafe in the 2024 edition?

    The environment is shared global state without thread-safe access from the C library. The unsafe block is a promise that nothing reads or writes it at the same time, for example at the very start of main.
  3. 3. What does Command::new("ls").arg("-l; rm -rf /") do?

    Command starts the program directly with the arguments you give. Without a shell, there is no special meaning for semicolons, so there is no shell injection.
  4. 4. What does process::exit(1) NOT do?

    exit ends the process at once: destructors of the values in scope are not run and unflushed BufWriters lose their data. Returning from main with an ExitCode lets destructors run.
  5. 5. How does a Rust program usually react to Ctrl+C gracefully?

    The standard library has no signal-receiving API. Handlers must do very little, so they set an atomic flag or send a message and the normal code does the shutdown.

Summary

  • env::args() starts with the program name; use .skip(1). Parse arguments in a function that takes them as a parameter, and use clap for real tools.
  • env::var returns Result<String, VarError>; unset and empty are different. Read configuration once into a struct and inject a lookup function for tests.
  • env::set_var and remove_var are unsafe in the 2024 edition because the process environment is not thread-safe; avoid mutating it.
  • A process ends with an exit code (0 for success). process::exit stops immediately without destructors; prefer returning ExitCode from main.
  • Command is a builder with no shell involved. status(), output() and spawn() differ in how the streams are handled. Check the exit status, close the child's stdin, avoid pipe deadlocks, and always wait for children.
  • The standard library cannot receive signals. Use a crate (ctrlc, tokio::signal, signal-hook) whose handler only sets a flag, and shut down from your normal code.

Next: Networking with std::net