温馨提示×

Rust如何与Linux系统进行交互

小樊
34
2026-04-19 10:03:05
栏目: 编程语言

Rust 是一种系统编程语言,它可以很好地与 Linux 系统进行交互。以下是一些 Rust 与 Linux 系统交互的方法:

1. 使用标准库

Rust 的标准库提供了许多与操作系统交互的基本功能,例如文件操作、进程管理、网络通信等。

文件操作

use std::fs::{File, OpenOptions};
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut file = OpenOptions::new().write(true).create(true).open("foo.txt")?;
    writeln!(file, "Hello, world!")?;
    Ok(())
}

进程管理

use std::process::{Command, Stdio};

fn main() {
    let output = Command::new("ls")
        .arg("-l")
        .stdout(Stdio::piped())
        .output()
        .expect("failed to execute process");

    println!("Status: {}", output.status);
    println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
}

网络通信

use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};

fn handle_client(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();
    println!("Received: {}", String::from_utf8_lossy(&buffer));

    let response = "Hello, client!";
    stream.write(response.as_bytes()).unwrap();
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:7878")?;

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                handle_client(stream);
            }
            Err(err) => {
                eprintln!("Error: {}", err);
            }
        }
    }

    Ok(())
}

2. 使用外部库

Rust 社区提供了许多外部库,这些库可以帮助你更方便地与 Linux 系统进行交互。

使用 libc

libc 是 Rust 的一个外部库,它提供了与 C 标准库兼容的接口。

extern crate libc;

use libc::{c_int, fork, execvp};

fn main() {
    unsafe {
        let pid = fork().expect("failed to fork");
        if pid == 0 {
            // Child process
            let args = ["ls", "-l"];
            execvp(args[0], args.as_ptr());
        } else {
            // Parent process
            println!("Child PID: {}", pid);
        }
    }
}

使用 nix

nix 是一个 Rust 库,它提供了许多与 Unix 系统交互的高级功能。

use nix::sys::wait::waitpid;
use nix::unistd::{fork, ForkResult};

fn main() {
    match fork() {
        Ok(ForkResult::Child) => {
            // Child process
            println!("Child PID: {}", nix::unistd::getpid());
        }
        Ok(ForkResult::Parent { child, .. }) => {
            // Parent process
            waitpid(child, None).expect("failed to wait for child");
        }
        Err(_) => {
            eprintln!("Failed to fork");
        }
    }
}

3. 使用系统调用

Rust 允许你直接使用系统调用,这提供了更高的灵活性和控制力。

use std::os::unix::net::{UnixListener, UnixStream};
use std::io::{Read, Write};

fn handle_client(mut stream: UnixStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();
    println!("Received: {}", String::from_utf8_lossy(&buffer));

    let response = "Hello, client!";
    stream.write(response.as_bytes()).unwrap();
}

fn main() -> std::io::Result<()> {
    let listener = UnixListener::bind("/tmp/rust.sock")?;

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                handle_client(stream);
            }
            Err(err) => {
                eprintln!("Error: {}", err);
            }
        }
    }

    Ok(())
}

通过这些方法,你可以使用 Rust 与 Linux 系统进行各种交互,包括文件操作、进程管理、网络通信等。

0