在 Linux 上用 Rust 进行系统编程的实用路线图
一 环境准备与工具链
curl https://sh.rustup.rs -sSf | shsource $HOME/.cargo/envrustc --version、cargo --versioncargo new hello_sys --bin && cd hello_syscargo build、cargo run二 用户态系统编程常见任务与示例
示例一 文件复制
use std::env;
use std::fs;
use std::io::Result;
fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
eprintln!("Usage: {} <src> <dst>", args[0]);
return Ok(());
}
fs::copy(&args[1], &args[2])?;
Ok(())
}
运行:cargo run source.txt destination.txt
示例二 简单 HTTP 服务
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use std::convert::Infallible;
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("Hello, Rust!")))
}
#[tokio::main]
async fn main() {
let make_svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle)) });
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}
运行:cargo run,访问 http://127.0.0.1:3000。
三 进阶 内核态 Rust 开发概览
sudo insmod hello_rust.ko 加载、sudo rmmod hello_rust 卸载,并用 dmesg 查看内核日志输出。四 实践建议与生态选择