fork

Function fork 

Source
pub fn fork(
    file_struct: &mut FileStruct,
    mm_struct: &mut MmStruct<LazyPager>,
    abi: &SyscallAbi<'_>,
    create_task: impl FnOnce(FileStruct, MmStruct<LazyPager>) -> ThreadBuilder,
) -> Result<usize, KernelError>
Expand description

Creates a new process by duplicating the current process using copy-on-write.

fork is a system call that creates a child process that is identical to the calling (parent) process. The child inherits the parent’s memory layout, file descriptors, and register state. After the fork, both processes continue execution independently from the point of the call.

This implementation uses copy-on-write (COW) to avoid eagerly copying the entire address space. Memory pages are initially shared between the parent and child and marked as read-only. When either process attempts to write to a shared page, a page fault occurs and LazyPager::do_copy_on_write handles creating a private writable copy of the page.

§Syscall API

int fork(void);

§Behavior

  • The parent receives the child’s PID as the return value.
  • The child receives 0 as the return value.
  • On failure, the parent receives Err(KernelError) and no new process is created.

§Memory Management

  • Invokes LazyPager::write_protect_ptes to mark shared pages as read-only.
  • Creates a new address space and page table for the child.
  • Invalidates stale TLB entries to enforce new memory protection rules.

§File Descriptors

  • Duplicates the parent’s file descriptor table.
  • File objects are shared and reference-counted across parent and child, consistent with the UNIX file model.

§ABI and Register State

  • Copies the parent’s ABI state into the child.
  • Adjusts the child’s register state to reflect a return value of 0.

§Parameters

  • file_struct: The parent’s file descriptor table to be duplicated.
  • mm_struct: The parent’s memory layout (address space).
  • abi: The parent’s syscall ABI and register snapshot.
  • create_task: A closure for creating and spawning the new process.

§Returns

  • Ok(pid): The parent receives the child process ID.
  • Err(KernelError): If the fork operation fails due to memory or resource constraints.