用 Rust 写 Linux 程序,本质上就是在 Linux 环境下用 Rust 编写原生应用,可以覆盖从命令行工具、系统服务到底层系统编程的各种场景。下面我按“从入门到进阶”的方式给你一个清晰路线。
在 Linux 上推荐使用官方工具:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装完成后:
source $HOME/.cargo/env
rustc --version
cargo --version
cargo new hello_linux
cd hello_linux
cargo run
src/main.rs:
fn main() {
println!("Hello, Linux!");
}
✅ 这已经是一个 Linux 原生可执行程序。
Rust 非常适合写 CLI。
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("参数: {:?}", args);
}
clap:强大的命令行参数解析anyhow / thiserror:错误处理[dependencies]
clap = { version = "4", features = ["derive"] }
use std::fs;
fn main() {
let content = fs::read_to_string("/etc/os-release").unwrap();
println!("{}", content);
}
use std::process::Command;
fn main() {
let output = Command::new("ls")
.arg("-l")
.output()
.unwrap();
println!("{}", String::from_utf8_lossy(&output.stdout));
}
Rust 可以直接调用 Linux 系统调用。
[dependencies]
libc = "0.2"
use libc::{fork, getpid};
fn main() {
unsafe {
let pid = fork();
if pid == 0 {
println!("子进程 PID: {}", getpid());
} else {
println!("父进程 PID: {}", getpid());
}
}
}
⚠️ unsafe 是必须的,因为系统调用不安全。
forksetsidsystemd/etc/systemd/system/myapp.service
[Unit]
Description=My Rust App
[Service]
ExecStart=/usr/local/bin/myapp
Restart=always
[Install]
WantedBy=multi-user.target
use std::net::TcpListener;
fn main() {
let listener = TcpListener::bind("0.0.0.0:8080").unwrap();
for stream in listener.incoming() {
println!("新连接: {:?}", stream);
}
}
常用库:
tokio(异步)axum / actix-web(Web 服务)cargo build --release
产物:
target/release/hello_linux
✅ 无运行时依赖(除了 libc)
可静态编译(musl):
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl
ctrlc = "3"
或自己用 libc::signal
getuidsetuidcapabilitiesinotifynotify crate如果你愿意,可以告诉我:
我可以直接给你一个可运行的完整示例工程。