Linux System Call `fork()` in Rust

Reading Time: 2 minutes

As we know, System calls provide an interface to the services that are available by the operating system. It is a mechanism in which a computer program requests a service from the kernel of the OS.

In this blog, I will cover fork() system call. fork() is used to create a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process. Both child and parent process have their unique process id. The child’s parent process id is same as parent process id.

In this blog, I will show how we can use fork() in Rust. Add nix in cargo.toml. This dependency provides Rust friendly bindings to *nix APIs.

nix = "0.18.0"

Now add the below code in main.rs

use nix::sys::wait::wait;
use nix::unistd::ForkResult::{Child, Parent};
use nix::unistd::{fork, getpid, getppid};


fn main() {
    let pid = fork();

    match pid.expect("Fork Failed: Unable to create child process!") {
        Child => println!(
            "Hello from child process with pid: {} and parent pid:{}",
            getpid(),
            getppid()
        ),
        Parent { child } => {
            wait();
            println!(
                "Hello from parent process with pid: {} and child pid:{}",
                getpid(),
                child
            );
        }
    }
}

When you will execute above program, you will see below output.

Hello from child process with pid: 130018 and parent pid:130005
Hello from parent process with pid: 130005 and child pid:130018

As you can see, the PID of the parent process is the PPID of the child process. So, the child process 130018 belongs to the parent process 130005.
I have also used wait() system call, which is used to wait in the parent process for the child process to finish.
This is a simple example. You can extend this example by modifying this code like running multiple child processes of same parent process. You can find source code here.

Thanks for reading the blog. If you want to read more content like this?  Subscribe Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe Rust Times Newsletter: https://bit.ly/2Vdlld7 .


Knoldus-blog-footer-image

Written by 

Ayush is the Sr. Lead Consultant @ Knoldus Software LLP. In his 10 years of experience he has become a developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality.