Rust Lang

Rust Std::OS in Linux

In Rust, the std::os module provides an abstraction over the operating system’s functionality. It allows us to interact with the underlying operating system to work with the environment variables, file system operations, process management, and more.

In this example, we will cover some fundamental operations that you can perform on Unix using the Rust std::os module.

It is good to remember that this is an extensive module and it contains many types and functions for various Unix-related operations. Therefore, please consider the documentation for reference on the corresponding processes.

Rust OS in Linux

In Linux, we can access the Unix-specific functions and types that are provided by the std::os::unix module, a sub-module of the std::os module in Rust.

This module is part of the Rust standard library and hence does not require you to install any external crate or dependencies.

Let us cover some basic API and operations that we can carry out on a Linux system from this module.

Accessing the Environment Variables

We can access the environment variables using the std::env module. For example, std::env::var(“PATH”) retrieves the value of the PATH environment variable.

Consider the following example program:

use std::env;
use std::ffi::OsString;

fn main() {
    // Access a specific environment variable
    if let Ok(value) = env::var("WAYLAND_DISPLAY") {
        println!("WAYLAND_DISPLAY={}", value);
    }

    // Iterate over all environment variables
    for (key, value) in env::vars_os() {
        let key_string = key.to_string_lossy();
        let value_string = value.to_string_lossy();
        println!("{}: {}", key_string, value_string);
    }

    // Access a specific environment variable as an `OsString`
    if let Some(value) = env::var_os("HOSTTYPE") {
        // Convert `OsString` to a `String` if needed
        if let Some(value_str) = value.to_str() {
            println!("HOSTTYPE={}", value_str);
        }
    }
}

 
In the given example, we start by importing the necessary modules. In this case, we are interested in the std::env and the std::ff::OsString.

To access a specific environment variable, we can use the env::var function and pass the name of the value that we wish to fetch. In this case, we get the value of the WAYLAND_DISPLAY variable.

The function returns the variable’s value as a result type.

We can also iterate over all the environment variables using the env::vars_os function. This returns an iterator with the key-value pairs of the environment variables. It is good to note that the values are returned as an OsString type. We can then convert them to string values using the to_string_lossy function.

We can also access the specific environment variables using the env::var_os function. This should return an <Option<OsString> type which we can convert to a string using the to_str() function.

The resulting output is as follows:

WAYLAND_DISPLAY=wayland-0
HOSTTYPE=x86_64

 

FS Operations Using the OS Module

As you can guess, the OS module provides various functions and methods to perform the filesystem-related operations.

Take the following program that demonstrates the various operations that we can perform using the std::os module in Linux:

use std::fs;

fn main() {
    // Read a file
    if let Ok(contents) = fs::read_to_string("/home/debian/.bashrc") {
        println!("bashrc: {}", contents);
    }

    // Create a new directory
    if let Err(err) = fs::create_dir("/home/debian/new_dir") {
        eprintln!("Failed to create directory: {}", err);
    }

    // Remove a file
    if let Err(err) = fs::remove_file("/home/debian/remove_me.txt") {
        eprintln!("Failed to remove file: {}", err);
    }
}

 
In the given example, we demonstrate how we can read the contents of a file using the fs::read_to_string() method. The method takes the path to the target file and returns the file contents as a string.

We can also create a new directory using the fs::create_dir() function and passing the path to the target directory as the parameter.

Finally, we can remove a specific file using the fs::remove_file() function and pass the target file as the parameter.

NOTE: The provided examples are some basic examples on how to perform the filesystem operations on Linux using the std::fs module. Rust provides a comprehensive collection of methods and functions which are demonstrated here. Refer to the documentation to learn more.

Process Management Using the OS Module

As you can guess, the OS module provides submodules and features to work with processes in the system.

Take the following example code:

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

fn main() {
    // run the ls command
    let output = Command::new("ls")
        .arg("-la")
        .output()
        .expect("Failed to execute command");

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        println!("Command output:\n{}", stdout);
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("Command failed:\n{}", stderr);
        exit(1);
    }
}

 
In the given example, we start by importing the required modules. In this case, we need the “command” and “exit” methods from the std::process submodule.

We then use the Command::new() function to run the “ls” command and pass the arguments to the command.

If successful, the command should return the directory listing for the current working directory as follows:

Conclusion

We explored how to use the various functions and methods that are provided by the std::os module and submodules to perform multiple operations in Linux and Unix-like systems. Remember that the std::os module is an extensive module that contains a broader collection of features than the ones that are demonstrated in this tutorial.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list