Skip to content

Rust examples

Exemplier (Rust version)

License

This subfolder contains the Rust version of the examples used in the operating systems course.

The examples are organized as a Cargo workspace (nix crate 0.30): cargo build at the root of exemplier-rust/ builds them all; cargo run -p process_05 runs one of them (or cargo run in its folder). Each example corresponds to the C file with the same name in ../exemplier/.

Program C equivalent Description
1_process/process_01 process_01.c fork(): parent and child each run their own part, the parent waits with waitpid()
1_process/process_02 process_02.c After fork(), each one modifies its own copy of a variable
1_process/process_03 process_03.c Parent and child blocked by sleep()
1_process/process_04a process_04a.c The parent never waits: the child becomes a zombie (state Z in ps); the parent sleeps with pause()
1_process/process_04b process_04b.c The parent dies before the child: the child becomes an orphan (getppid() changes)
1_process/process_05 process_05.c The parent waits for the child and decodes its status: exit code or signal (WaitStatus::Exited / Signaled)
1_process/process_06a process_06a.c The child is replaced by ls -al (CommandExt::exec())
1_process/process_06b process_06b.c The child is replaced by gnuplot, which plots command.gp (run it in this folder)
1_process/process_07 process_07.c Process groups: setpgid(0, 0) in the child and the parent, then kill(-pgid, SIGTERM)
3_files/file_copy file_copy.c Copies keyboard input to file.out with read()/write(), partial writes handled
3_files/fs_block fs_block.c statvfs(): block size and number of blocks, counted in f_frsize

Using fork() is considered unsafe in Rust. Each program includes a comment (// SAFETY:) explaining why the call is safe in this context.

These code examples are provided under the Apache 2.0 License.

Sources

1_process/process_01/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive.

use nix::sys::wait::waitpid;
use nix::unistd::{fork, ForkResult};
use std::process::{self, exit};

/// Manages the child process.
fn manage_child() {
    println!("Child process (PID n° {})", process::id());
    println!("Instructions of child process...");
}

/// Manages the parent process.
fn manage_parent() {
    println!("Parent process (PID n° {})", process::id());
    println!("Instructions of parent process...");
}

fn main() {
    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(),
        Ok(ForkResult::Parent { child }) => {
            manage_parent();
            if let Err(err) = waitpid(child, None) {
                eprintln!("Error [waitpid()]: {}", err);
                exit(1);
            }
        }
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_02/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive and
//! shows the evolution of a variable in parent and child processes: each one
//! modifies its own copy.

use nix::sys::wait::waitpid;
use nix::unistd::{fork, ForkResult};
use std::process::{self, exit};

/// Manages the child process.
fn manage_child(parameter: &mut i32) {
    println!("Child process (PID n° {})", process::id());
    println!("Child modifies its own variable...");
    *parameter = 20;
}

/// Manages the parent process.
fn manage_parent(parameter: &mut i32) {
    println!("Parent process (PID n° {})", process::id());
    println!("Parent modifies its own variable...");
    *parameter = 10;
}

fn main() {
    let mut own_variable = 0;

    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => {
            manage_child(&mut own_variable);
            println!(
                "PID n° {} has its own variable equal to: {}",
                process::id(),
                own_variable
            );
        }
        Ok(ForkResult::Parent { child }) => {
            manage_parent(&mut own_variable);
            println!(
                "PID n° {} has its own variable equal to: {}",
                process::id(),
                own_variable
            );
            if let Err(err) = waitpid(child, None) {
                eprintln!("Error [waitpid()]: {}", err);
                exit(1);
            }
        }
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_03/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive and uses
//! sleep() to block parent and child processes.

use nix::sys::wait::waitpid;
use nix::unistd::{fork, sleep, ForkResult};
use std::process::{self, exit};

/// Manages the child process: it is blocked during `duration` seconds.
fn manage_child(duration: u32) {
    println!("Child process (PID n° {})", process::id());
    println!("Child will be blocked during {} seconds...", duration);
    sleep(duration);
    println!("Child has finished to sleep.");
}

/// Manages the parent process: it is blocked during `duration` seconds, then
/// waits for its child.
fn manage_parent(duration: u32) {
    println!("Parent process (PID n° {})", process::id());
    println!("Parent will be blocked during {} seconds...", duration);
    sleep(duration);
    println!("Parent has finished to sleep.");
}

fn main() {
    let duration = 5;

    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(duration),
        Ok(ForkResult::Parent { child }) => {
            manage_parent(duration);
            if let Err(err) = waitpid(child, None) {
                eprintln!("Error [waitpid()]: {}", err);
                exit(1);
            }
        }
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_04a/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive, but
//! the parent never waits for its child, which then becomes a zombie!
//! Observe it with `ps -o pid,ppid,stat,comm` (state Z), then stop the parent
//! with Ctrl-C.

use nix::unistd::{fork, pause, sleep, ForkResult};
use std::process::{self, exit};

/// Manages the child process: it is blocked during `duration` seconds, then
/// ends.
fn manage_child(duration: u32) {
    println!("Child process (PID n° {})", process::id());
    println!("Child will be blocked during {} seconds...", duration);
    sleep(duration);
    println!("Child has finished to sleep: it is now a zombie.");
}

/// Manages the parent process: it never waits for its child. It sleeps with
/// pause() (no CPU used, unlike an empty `loop {}`) until a signal ends it.
fn manage_parent() -> ! {
    println!("Parent process (PID n° {})", process::id());
    println!("Parent will never wait for its child to finish (Ctrl-C to stop).");
    loop {
        pause();
    }
}

fn main() {
    let duration = 5;

    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(duration),
        Ok(ForkResult::Parent { child: _ }) => manage_parent(),
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_04b/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive, and
//! where the parent process dies before its child. The child process becomes
//! an orphan: its new parent is init (or a subreaper), see `getppid()`.

use nix::unistd::{fork, getppid, sleep, ForkResult};
use std::process::{self, exit};

/// Manages the child process: it is blocked during `duration` seconds.
fn manage_child(duration: u32) {
    println!(
        "Child process (PID n° {}), parent {}",
        process::id(),
        getppid()
    );
    println!("Child will be blocked during {} seconds...", duration);
    sleep(duration);
    println!(
        "Child has finished to sleep; its parent is now {}.",
        getppid()
    );
}

/// Manages the parent process: it does not wait for its child and dies.
fn manage_parent() {
    println!("Parent process (PID n° {})", process::id());
    println!("Dying...");
}

fn main() {
    let duration = 20;

    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(duration),
        Ok(ForkResult::Parent { child: _ }) => manage_parent(),
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_05/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive. The
//! parent waits for its child to finish and decodes its status.

use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, getpid, getppid, sleep, ForkResult};
use std::process::{self, exit};

/// Manages the child process: it is blocked during `duration` seconds.
fn manage_child(duration: u32) {
    println!("Child process (PID n° {})", process::id());
    println!("Child will be blocked during {} seconds...", duration);
    sleep(duration);
    println!("Child has finished to sleep.");
    println!("The PID of my parent is {}.", getppid());
}

/// Manages the parent process before it waits for its child.
fn manage_parent() {
    println!(
        "Parent process (PID n° {}) is waiting for the child to finish.",
        process::id()
    );
}

/// Displays how the child ended: exit code (WIFEXITED) or signal (WIFSIGNALED).
fn report(status: WaitStatus) {
    match status {
        WaitStatus::Exited(child, code) => {
            println!(
                "{} : child {} has finished (exit code: {})",
                getpid(),
                child,
                code
            );
        }
        WaitStatus::Signaled(child, signal, _core_dumped) => {
            println!(
                "{} : child {} was killed by the signal {:?}",
                getpid(),
                child,
                signal
            );
        }
        other => println!("{} : other status {:?}", getpid(), other),
    }
}

fn main() {
    let duration = 20;

    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(duration),
        Ok(ForkResult::Parent { child }) => {
            manage_parent();
            match waitpid(child, None) {
                Ok(status) => report(status),
                Err(err) => {
                    eprintln!("Error [waitpid()]: {}", err);
                    exit(1);
                }
            }
        }
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_06a/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program that clones a process using the fork() primitive. The
//! child is replaced by a new program (`ls -al`) using exec.

use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, getpid, ForkResult};
use std::os::unix::process::CommandExt;
use std::process::{self, exit, Command};

/// Manages the child process: it is replaced by the "ls" command.
fn manage_child() -> ! {
    println!("Child process (PID n° {})", process::id());
    println!("Child is going to be replaced by \"ls\" command.");
    // CommandExt::exec() replaces the process (execvp(): a name without '/'
    // is searched in PATH). It only returns on failure.
    let err = Command::new("/bin/ls").args(["-al"]).exec();
    eprintln!("Error [exec()] ls: {}", err);
    exit(127);
}

/// Manages the parent process before it waits for its child.
fn manage_parent() {
    println!(
        "Parent process (PID n° {}) waiting for the child.",
        process::id()
    );
}

/// Displays how the child ended: exit code (WIFEXITED) or signal (WIFSIGNALED).
fn report(status: WaitStatus) {
    match status {
        WaitStatus::Exited(child, code) => {
            println!(
                "{} : child {} has finished (exit code: {})",
                getpid(),
                child,
                code
            );
        }
        WaitStatus::Signaled(child, signal, _core_dumped) => {
            println!(
                "{} : child {} was killed by the signal {:?}",
                getpid(),
                child,
                signal
            );
        }
        other => println!("{} : other status {:?}", getpid(), other),
    }
}

fn main() {
    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(),
        Ok(ForkResult::Parent { child }) => {
            manage_parent();
            match waitpid(child, None) {
                Ok(status) => report(status),
                Err(err) => {
                    eprintln!("Error [waitpid()]: {}", err);
                    exit(1);
                }
            }
        }
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_06b/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Another program that clones a process using the fork() primitive. The
//! child is replaced by gnuplot, which draws the script `command.gp`.
//! Run it from this directory (`cargo run`): the path of the script is relative.

use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, getpid, ForkResult};
use std::os::unix::process::CommandExt;
use std::process::{self, exit, Command};

/// Manages the child process: it is replaced by gnuplot ("gnuplot" is a name
/// searched in PATH).
fn manage_child() -> ! {
    println!("Child process (PID n° {})", process::id());
    println!("Child is going to be replaced by Gnuplot program.");
    // CommandExt::exec() replaces the process (execvp(): a name without '/'
    // is searched in PATH). It only returns on failure.
    let err = Command::new("gnuplot")
        .args(["-persist", "command.gp"])
        .exec();
    eprintln!("Error [exec()] gnuplot: {}", err);
    exit(127);
}

/// Manages the parent process before it waits for its child.
fn manage_parent() {
    println!(
        "Parent process (PID n° {}) waiting for the child.",
        process::id()
    );
}

/// Displays how the child ended: exit code (WIFEXITED) or signal (WIFSIGNALED).
fn report(status: WaitStatus) {
    match status {
        WaitStatus::Exited(child, code) => {
            println!(
                "{} : child {} has finished (exit code: {})",
                getpid(),
                child,
                code
            );
        }
        WaitStatus::Signaled(child, signal, _core_dumped) => {
            println!(
                "{} : child {} was killed by the signal {:?}",
                getpid(),
                child,
                signal
            );
        }
        other => println!("{} : other status {:?}", getpid(), other),
    }
}

fn main() {
    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(),
        Ok(ForkResult::Parent { child }) => {
            manage_parent();
            match waitpid(child, None) {
                Ok(status) => report(status),
                Err(err) => {
                    eprintln!("Error [waitpid()]: {}", err);
                    exit(1);
                }
            }
        }
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
1_process/process_07/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A simple program about a process and its group.
//!
//! The child leaves the group of its parent with setpgid(0, 0): it becomes the
//! leader of a new group whose PGID is its PID. The parent makes the same call
//! (setpgid(pid, pid)), so that the group exists whoever runs first, then sends
//! SIGTERM to the whole group with kill(-pgid, SIGTERM).
//!
//! Course "Operating Systems", chapter "Signaux", slide "Groupes de processus".

use nix::sys::signal::{kill, Signal};
use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, getpgrp, getpid, pause, setpgid, sleep, ForkResult, Pid};
use std::io::{self, Write};
use std::process::{self, exit};

/// Manages the child process: it creates its own group, then waits.
fn manage_child() -> ! {
    println!(
        "Child process: PID={}, Group ID={}",
        process::id(),
        getpgrp()
    );

    // New group, led by the child: PGID = PID of the child
    if let Err(err) = setpgid(Pid::from_raw(0), Pid::from_raw(0)) {
        eprintln!("Error [setpgid()] (child): {}", err);
        exit(1);
    }
    println!(
        "Child process: PID={}, new Group ID={}",
        process::id(),
        getpgrp()
    );
    io::stdout().flush().ok(); // killed by SIGTERM: nothing must stay in a buffer

    loop {
        pause(); // waits for the SIGTERM of its parent
    }
}

/// Displays how the child ended: exit code (WIFEXITED) or signal (WIFSIGNALED).
fn report(status: WaitStatus) {
    match status {
        WaitStatus::Exited(child, code) => {
            println!(
                "{} : child {} has finished (exit code: {})",
                getpid(),
                child,
                code
            );
        }
        WaitStatus::Signaled(child, signal, _core_dumped) => {
            println!(
                "{} : child {} was killed by the signal {:?}",
                getpid(),
                child,
                signal
            );
        }
        other => println!("{} : other status {:?}", getpid(), other),
    }
}

/// Manages the parent process: displays its group, sends SIGTERM to the group
/// of the child, then waits for it.
fn manage_parent(child: Pid) {
    println!(
        "Parent process: PID={}, Group ID={}",
        process::id(),
        getpgrp()
    );

    // Same call as in the child: no race on who runs first
    if let Err(err) = setpgid(child, child) {
        eprintln!("Error [setpgid()] (parent): {}", err);
    }
    sleep(1); // let the child display its new group

    println!("Parent: SIGTERM to the group {}", child);
    // -pgid: the whole group (killpg(pgid, SIGTERM) does the same)
    if let Err(err) = kill(Pid::from_raw(-child.as_raw()), Signal::SIGTERM) {
        eprintln!("Error [kill()]: {}", err);
        exit(1);
    }

    match waitpid(child, None) {
        Ok(status) => report(status),
        Err(err) => {
            eprintln!("Error [waitpid()]: {}", err);
            exit(1);
        }
    }
}

fn main() {
    // SAFETY: fork() is unsafe in Rust because, in a multi-threaded program,
    // the child only gets a copy of the calling thread (a lock held by another
    // thread would stay locked forever). This program has a single thread.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => manage_child(),
        Ok(ForkResult::Parent { child }) => manage_parent(child),
        Err(err) => {
            eprintln!("Error [fork()]: {}", err);
            exit(1);
        }
    }
}
3_files/file_copy/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Copies the text typed on the keyboard to a file named file.out.
//! Reads input from stdin in 80-byte chunks until EOF (Ctrl+D).

use nix::fcntl::{open, OFlag};
use nix::sys::stat::Mode;
use nix::unistd::{read, write};
use std::io;
use std::os::fd::{AsFd, BorrowedFd};
use std::process::exit;

const SIZE: usize = 80;

/// Writes the whole buffer: write() may write fewer bytes than asked (partial
/// write), so it is called again on the rest (`ecrire_n()` in the C course).
fn write_all(fd: BorrowedFd, mut buffer: &[u8]) -> nix::Result<()> {
    while !buffer.is_empty() {
        let written = write(fd, buffer)?;
        buffer = &buffer[written..];
    }
    Ok(())
}

fn main() {
    // The OwnedFd returned by open() closes the file when it goes out of scope
    let file = open(
        "file.out",
        OFlag::O_CREAT | OFlag::O_WRONLY | OFlag::O_TRUNC,
        Mode::from_bits_truncate(0o644),
    )
    .unwrap_or_else(|err| {
        eprintln!("Error [open()] file.out: {}", err);
        exit(1);
    });

    let stdin = io::stdin();
    let stdout = io::stdout();
    if let Err(err) = write_all(stdout.as_fd(), b"Type your input (Ctrl+D to end):\n") {
        eprintln!("Error [write()] prompt: {}", err);
        exit(1);
    }

    let mut buffer = [0u8; SIZE];
    loop {
        match read(stdin.as_fd(), &mut buffer) {
            Ok(0) => break, // EOF
            Ok(n) => {
                if let Err(err) = write_all(file.as_fd(), &buffer[..n]) {
                    eprintln!("Error [write()] file.out: {}", err);
                    exit(1);
                }
            }
            Err(err) => {
                eprintln!("Error [read()] stdin: {}", err);
                exit(1);
            }
        }
    }
    // `file` is closed here (drop of the OwnedFd)
}
3_files/fs_block/src/main.rs

View on GitHub

// Unix System Programming Examples / Exemplier de programmation système Unix
//
// Copyright (C) 1995-2026 Alain Lebret
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Uses statvfs() to display the filesystem statistics (block size, total,
//! free and available blocks) for the path given as a command-line argument.
//!
//! The block counts are expressed in units of the fragment size (f_frsize),
//! which may differ from the block size (f_bsize): on macOS, f_bsize is 1 MiB
//! and f_frsize 4 KiB.

use nix::sys::statvfs::statvfs;
use std::env;
use std::process::exit;

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 2 {
        eprintln!(
            "Usage: {} <path to any directory or file on the target filesystem>",
            args[0]
        );
        exit(1);
    }

    let stat = statvfs(args[1].as_str()).unwrap_or_else(|err| {
        eprintln!("Error [statvfs()]: {}", err);
        exit(1);
    });

    let unit = stat.fragment_size() as u64; // unit of the counts below
    let gib = |blocks: u64| blocks * unit / (1024 * 1024 * 1024);

    println!(
        "Filesystem block size (f_bsize): {} bytes",
        stat.block_size()
    );
    println!(
        "Fragment size (f_frsize, unit of the counts): {} bytes",
        unit
    );
    println!(
        "Total blocks: {} ({} GiB)",
        stat.blocks(),
        gib(stat.blocks() as u64)
    );
    println!(
        "Free blocks: {} ({} GiB)",
        stat.blocks_free(),
        gib(stat.blocks_free() as u64)
    );
    println!(
        "Available blocks (non-superuser): {} ({} GiB)",
        stat.blocks_available(),
        gib(stat.blocks_available() as u64)
    );
}