Function nix::unistd::fork

source ·
pub unsafe fn fork() -> Result<ForkResult>
Expand description

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

After successfully calling the fork system call, a second process will be created which is identical to the original except for the pid and the return value of this function. As an example:

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

match unsafe{fork()} {
   Ok(ForkResult::Parent { child, .. }) => {
       println!("Continuing execution in parent process, new child has pid: {}", child);
       waitpid(child, None).unwrap();
   }
   Ok(ForkResult::Child) => {
       // Unsafe to use `println!` (or `unwrap`) here. See Safety.
       write(std::io::stdout(), "I'm a new child process\n".as_bytes()).ok();
       unsafe { libc::_exit(0) };
   }
   Err(_) => println!("Fork failed"),
}

This will print something like the following (order nondeterministic). 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

§Safety

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.