fork

Function fork 

Source
pub fn fork() -> Result<Fork>
Expand description

Create a new child process see fork(2)

Upon successful completion, fork() returns Fork::Child in the child process and Fork::Parent(pid) with the child’s process ID in the parent process.

Example:

use fork::{fork, Fork};

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

This will print something like the following (order indeterministic).

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

The thing to note is that you end up with two processes continuing execution immediately after the fork call but with different match arms.

§Safety Considerations

After calling fork(), the child process is an exact copy of the parent process. However, there are important safety considerations:

  • File Descriptors: Inherited from parent but share the same file offset and status flags. Changes in one process affect the other.
  • Mutexes and Locks: May be in an inconsistent state in the child. Only the thread that called fork() exists in the child; other threads disappear mid-execution, potentially leaving mutexes locked.
  • Async-Signal-Safety: Between fork() and exec(), only async-signal-safe functions should be called. This includes most system calls but excludes most library functions, memory allocation, and I/O operations.
  • Signal Handlers: Inherited from parent but should be used carefully in multi-threaded programs.
  • Memory: Child gets a copy-on-write copy of parent’s memory. Large memory usage can impact performance.

For detailed information, see the fork(2) man page.

§nix::unistd::fork

The example has been taken from the nix::unistd::fork, please check the Safety section

§Errors

Returns an io::Error if the fork system call fails. Common errors include:

  • Resource temporarily unavailable (EAGAIN) - process limit reached
  • Out of memory (ENOMEM)