Fork

The memory layout between parent process and child process

what they shared

  • Address Space

    • Code segments
    • Shared memory segments
  • Open file table(Exactly, parent and child didn't shared the same open file table, is duplicate)

  • User ID, Group ID,

  • Session ID

  • Controlling terminal

  • Current working directory

  • Root directory

  • File mode creation mask

  • Signal mask and dispositions

  • Environment

  • Memory mappings

  • Resource limits

File shareing

All file descriptors that are open in the parent are duplicated in the child.Next figure shown sharing open files between parent and child after fork.

parent and child concurrent write the same file

It is important that the parent and the child share the same file offset. This is ensured if both parent and child write to the same descriptor, without any form of synchronization, such as having the parent wait for the child, their output will be intermixed (assuming it’s a descriptor that was open before the fork ) .

Two process concurrent write the same file

Now consider this situation, two standalone process open the same file and write without synchronization. In this situation , these two process maintain their own file offset and this may eventually lead the output be overwritten rather than intermixed.

Copy on Write
  1. Data Segment (global variable, static variable)

  2. Heap

what they don’t shared
  1. The return values from fork are different.

  2. The process IDs are different.

  3. The two processes have different parent process IDs: the parent process ID of the child is the parent; the parent process ID of the parent doesn’t change.

  4. The child’s tms_utime , tms_stime , tms_cutime , and tms_cstime values are set to 0

  5. File locks set by the parent are not inherited by the child.

  6. Pending alarms are cleared for the child.

  7. The set of pending signals for the child is set to the empty set.

vfork

The vfork function was intended to create a new process for the purpose of executing a new program. The vfork function creates the new process, just like fork , except three main differences.

  • without copying the address space of the parent into the child, as the child won’t reference that address space; the child simply calls exec (or exit ) right after the vfork .

  • No copy-on-write, if child didn’t call exec or exitafter vfork, the child run on parent address space, and the child can modify the memory of mapping with parent.

  • vfork guarantees that the child runs first, until the child calls `exec` or `exit`.

Both fork, vfork and pthread_create are wrappers in glibc and are implemented via the clone() system call through passing different flags parameter.

Better understand these topic reference this page.

https://unix.stackexchange.com/questions/87551/which-file-in-kernel-specifies-fork-vfork-to-use-sys-clone-system-call

results matching ""

    No results matching ""