Skip to main content
Be Bitwise
RustRust Systems Programming

Working with the OS

Rust's standard library wraps the OS in safe, cross-platform abstractions. Spawn processes, catch signals, juggle environment variables, grab file locks. The same safety guarantees apply throughout.

Spawning Processes

std::process::Command builds and executes external commands:

rust
use std::process::Command;
fn main() {
// Simple command
let output = Command::new("ls")
.arg("-la")
.arg("/tmp")
.output()
.expect("Failed to execute ls");
println!("Status: {}", output.status);
println!("Stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("Stderr: {}", String::from_utf8_lossy(&output.stderr));
}

You can also pipe between commands:

rust
use std::process::{Command, Stdio};
fn main() {
let ls = Command::new("ls")
.stdout(Stdio::piped())
.spawn()
.expect("Failed to start ls");
let grep = Command::new("grep")
.arg(".rs")
.stdin(ls.stdout.unwrap())
.output()
.expect("Failed to start grep");
println!("{}", String::from_utf8_lossy(&grep.stdout));
}
Key Concept

Command is a builder. Each method hands back &mut Command, so calls chain. spawn() kicks the process off and returns. output() waits for it to finish, slurping up stdout and stderr along the way.

Signal Handling

The standard library skips signal handling, but the ctrlc crate fills the gap with a portable Ctrl+C hook:

rust
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
fn main() {
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();
ctrlc::set_handler(move || {
println!("\nReceived Ctrl+C, shutting down...");
r.store(false, Ordering::SeqCst);
}).expect("Error setting Ctrl+C handler");
println!("Running. Press Ctrl+C to stop.");
while running.load(Ordering::SeqCst) {
// Main work loop
std::thread::sleep(std::time::Duration::from_millis(100));
}
println!("Shutdown complete.");
}

On Unix, when you need richer signal handling, reach for signal-hook:

rust
use signal_hook::consts::{SIGTERM, SIGHUP};
use signal_hook::iterator::Signals;
use std::thread;
fn main() {
let mut signals = Signals::new(&[SIGTERM, SIGHUP]).unwrap();
thread::spawn(move || {
for sig in signals.forever() {
match sig {
SIGTERM => {
println!("Received SIGTERM");
// Only ends this listener thread. Tell main to stop too,
// e.g. with an AtomicBool as in the ctrlc example
break;
}
SIGHUP => {
println!("Received SIGHUP - reloading config");
}
_ => unreachable!(),
}
}
});
// Main application loop...
}

Environment Variables

rust
use std::env;
fn main() {
// Read a variable
match env::var("HOME") {
Ok(val) => println!("HOME = {}", val),
Err(e) => println!("HOME not set: {}", e),
}
// Set a variable (for this process and children)
env::set_var("MY_APP_MODE", "production"); // `unsafe` in the 2024 edition
// Iterate all variables
for (key, value) in env::vars() {
println!("{} = {}", key, value);
}
// Command-line arguments
let args: Vec<String> = env::args().collect();
println!("Program: {}", args[0]);
for arg in &args[1..] {
println!("Arg: {}", arg);
}
}

In the 2024 edition env::set_var is an unsafe fn, because changing the environment while another thread reads it is a data race inside libc. If all you want is to hand a variable to a child process, Command::env sets it for that child alone and needs no unsafe.

File Locking

File locks coordinate access across processes. For years the fs2 crate was the usual way to get them, and you'll still meet it in older code, though it hasn't seen a release in a long time:

rust
use std::fs::File;
use fs2::FileExt;
fn main() -> std::io::Result<()> {
let file = File::create("/tmp/myapp.lock")?;
// Exclusive lock (blocks until available)
file.lock_exclusive()?;
println!("Lock acquired, doing work...");
// Critical section
std::thread::sleep(std::time::Duration::from_secs(5));
file.unlock()?;
println!("Lock released.");
Ok(())
}

Since Rust 1.89, std::fs::File has lock, lock_shared, try_lock and unlock of its own, so new code on a recent toolchain should skip the crate: swap lock_exclusive() for lock() and drop the use fs2::FileExt line.

Current Directory and Paths

rust
use std::env;
use std::path::{Path, PathBuf};
fn main() {
// Current directory
let cwd = env::current_dir().unwrap();
println!("CWD: {}", cwd.display());
// Change directory
env::set_current_dir("/tmp").unwrap();
// Home directory
let home = env::var("HOME").unwrap();
let config_path = PathBuf::from(&home).join(".config").join("myapp");
println!("Config: {}", config_path.display());
// Executable path
let exe = env::current_exe().unwrap();
println!("Running from: {}", exe.display());
}

Exit Codes

rust
use std::process;
fn main() {
if !check_prerequisites() {
eprintln!("Prerequisites not met");
process::exit(1);
}
// Normal execution
println!("All good");
// Implicit exit(0)
}

A supervisor also needs to know how a child ended. On Unix there are two ways out: the child exits with a code, or a signal kills it, and ExitStatus keeps them apart (code() for one, signal() from ExitStatusExt for the other). The runner launches itself three times in different modes to show both.

Try itAdd a panic mode that calls panic!(), run it, and predict whether it comes back as a code or a signal.
Rust (1.40.0)

Practical Example: A Process Supervisor

rust
use std::process::{Command, Child};
use std::time::{Duration, Instant};
struct Supervisor {
command: String,
args: Vec<String>,
max_restarts: usize,
restart_delay: Duration,
}
impl Supervisor {
fn run(&self) {
let mut restarts = 0;
loop {
println!("Starting: {} {:?}", self.command, self.args);
let start = Instant::now();
let mut child = Command::new(&self.command)
.args(&self.args)
.spawn()
.expect("Failed to start process");
let status = child.wait().expect("Failed to wait for process");
let runtime = start.elapsed();
println!("Process exited with: {} (ran for {:?})", status, runtime);
if status.success() {
println!("Clean exit, not restarting.");
break;
}
restarts += 1;
if restarts > self.max_restarts {
eprintln!("Max restarts ({}) exceeded, giving up.", self.max_restarts);
break;
}
println!("Restarting in {:?}... (attempt {}/{})",
self.restart_delay, restarts, self.max_restarts);
std::thread::sleep(self.restart_delay);
}
}
}

OS work in Rust feels natural — the standard library hands you ergonomic, safe wrappers over the underlying syscalls. The type system swats away the usual mistakes: ignored errors, misplaced arguments, the lot.