Function nix::unistd::fork[][src]

pub unsafe fn fork() -> Result<ForkResult>

Create a new child process duplicating the parent process (see fork(2)).

After calling the fork system call (successfully) two processes will be created that are identical with the exception of their pid and the return value of this function. As an example:

use nix::unistd::{fork, ForkResult};

match unsafe{fork()} {
   Ok(ForkResult::Parent { child, .. }) => {
       println!("Continuing execution in parent process, new child has pid: {}", child);
   Ok(ForkResult::Child) => println!("I'm a new child process"),
   Err(_) => println!("Fork failed"),

This will print something like the following (order indeterministic). The thing to note is that you end up with two processes continuing execution immediately after the fork call but with different match arms.

Continuing execution in parent process, new child has pid: 1234
I'm a new child process


In a multithreaded program, only async-signal-safe functions like pause and _exit may be called by the child (the parent isn't restricted). Note that memory allocation may not be async-signal-safe and thus must be prevented.

Those functions are only a small subset of your operating system's API, so special care must be taken to only invoke code you can control and audit.