Bird
Raised Fist0
Operating Systemsknowledge~6 mins

Process creation (fork and exec) in Operating Systems - Full Explanation

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Imagine you want your computer to start a new task, like opening a program. The system needs a way to create a new process that can run this task separately. This is where process creation comes in, using two main steps: making a copy of an existing process and then replacing it with a new program.
Explanation
Fork: Creating a copy
The fork operation makes a new process by copying the current one. This new process is almost identical to the original, including its code and data. Both processes continue running independently after the fork, but they have different process IDs.
Fork creates a new process by duplicating the current one.
Exec: Running a new program
After fork, the new process often needs to run a different program. The exec operation replaces the current process's code and data with a new program loaded from disk. This means the process keeps its ID but changes what it is doing.
Exec replaces a process's program with a new one.
Why use fork and exec together?
Using fork and exec together allows the system to create a new process and then run a different program in it. This two-step method gives control over the new process before it starts the new program, such as setting up resources or environment.
Fork and exec combined let a process create and run a new program.
Real World Analogy

Imagine you have a recipe book and want to make a new dish. First, you make a photocopy of the recipe (fork), so you have your own copy to work on. Then, you erase the copied recipe and write a new one on it (exec), so your copy now has a different recipe to follow.

Fork: Creating a copy → Making a photocopy of the recipe book page
Exec: Running a new program → Erasing the copied recipe and writing a new one
Why use fork and exec together? → Copying the recipe first, then changing it to a new recipe
Diagram
Diagram
┌─────────────┐        fork        ┌─────────────┐
│ Parent Proc │ ───────────────▶ │ Child Proc  │
│ (Program A) │                  │ (Program A) │
└─────────────┘                  └─────────────┘
                                   │
                                   │ exec
                                   ▼
                             ┌─────────────┐
                             │ Child Proc  │
                             │ (Program B) │
                             └─────────────┘
This diagram shows a parent process creating a child process with fork, then the child process replacing its program with exec.
Key Facts
ProcessA running instance of a program with its own memory and resources.
ForkAn operation that creates a new process by copying an existing one.
ExecAn operation that replaces a process's program with a new program.
Process ID (PID)A unique number identifying a process in the system.
Parent processThe original process that creates a new child process.
Child processThe new process created by fork, initially a copy of the parent.
Code Example
Operating Systems
import os

pid = os.fork()
if pid == 0:
    # Child process
    os.execvp('ls', ['ls', '-l'])
else:
    # Parent process
    print(f"Parent process, child PID: {pid}")
OutputSuccess
Common Confusions
Fork creates a completely new program from scratch.
Fork creates a completely new program from scratch. Fork copies the existing process; it does not load a new program until exec is called.
Exec creates a new process.
Exec creates a new process. Exec replaces the program in the current process; it does not create a new process.
Parent and child processes share the same memory after fork.
Parent and child processes share the same memory after fork. They start as copies but have separate memory spaces; changes in one do not affect the other.
Summary
Fork creates a new process by copying the current one, giving it a unique ID.
Exec replaces the program in a process with a new program, changing what it runs.
Together, fork and exec let the system start new programs in separate processes.

Practice

(1/5)
1. What does the fork() system call do in an operating system?
easy
A. Replaces the current process with a new program
B. Creates a new process by copying the current process
C. Terminates the current process immediately
D. Pauses the current process temporarily

Solution

  1. Step 1: Understand the role of fork()

    The fork() call creates a new process by duplicating the current one, including its code and data.
  2. Step 2: Differentiate from exec()

    Unlike exec(), which replaces the process, fork() makes a copy, so both processes continue running.
  3. Final Answer:

    Creates a new process by copying the current process -> Option B
  4. Quick Check:

    fork() = process copy [OK]
Hint: Remember: fork copies, exec replaces [OK]
Common Mistakes:
  • Confusing fork() with exec()
  • Thinking fork() replaces the process
  • Believing fork() pauses the process
2. Which of the following is the correct way to use exec() in a program?
easy
A. exec("ls -l")
B. exec("/bin/ls", "-l")
C. exec("/bin/ls", ["ls", "-l"])
D. exec("ls", "-l")

Solution

  1. Step 1: Recall exec() syntax

    The exec() family requires the program path and an argument list, where the first argument is the program name.
  2. Step 2: Identify correct argument format

    exec("/bin/ls", ["ls", "-l"]) correctly passes the path and an array with the program name and its argument.
  3. Final Answer:

    exec("/bin/ls", ["ls", "-l"]) -> Option C
  4. Quick Check:

    exec() needs path + argument list [OK]
Hint: exec() needs program path and argument array [OK]
Common Mistakes:
  • Passing arguments as separate strings instead of array
  • Using command line string instead of path
  • Omitting the program name in argument list
3. Consider this code snippet in a Unix-like system:
pid = fork()
if pid == 0:
    exec("/bin/echo", ["echo", "Hello"])
else:
    print("Parent process")

What will be printed when this code runs?
medium
A. Parent process Hello
B. Parent process
C. Hello
D. Hello Parent process

Solution

  1. Step 1: Understand fork() behavior

    The fork() creates a child process. The child runs the exec() replacing itself with the echo program.
  2. Step 2: Analyze output from parent and child

    The parent (pid > 0) prints "Parent process". The child (pid == 0) calls exec(), loading /bin/echo which prints "Hello". Both outputs appear on stdout, typically with parent first.
  3. Final Answer:

    Parent process Hello -> Option A
  4. Quick Check:

    fork() + child exec() = both print [OK]
Hint: fork() child exec(): both print, parent first [OK]
Common Mistakes:
  • Thinking only parent prints
  • Reversing the output order
  • Believing exec() prevents child output
4. What is wrong with this code snippet?
pid = fork()
if pid == 0:
    exec("ls", ["ls", "-l"])
else:
    print("Parent")
medium
A. The exec call is missing the full path to the program
B. fork() should be replaced with exec()
C. The parent process should call exec() instead
D. The argument list to exec() should be a string, not a list

Solution

  1. Step 1: Check exec() usage

    The exec() call requires the full path to the executable, not just the command name.
  2. Step 2: Identify the missing full path

    Using "ls" without "/bin/ls" will cause exec to fail because it won't find the program.
  3. Final Answer:

    The exec call is missing the full path to the program -> Option A
  4. Quick Check:

    exec() needs full path [OK]
Hint: Always use full path in exec() [OK]
Common Mistakes:
  • Using command name without path in exec()
  • Confusing fork() and exec() roles
  • Passing wrong argument types to exec()
5. A program wants to run another program safely without stopping itself. Which sequence of system calls should it use?
hard
A. Call exec() first, then fork()
B. Call exec() directly to run the new program
C. Call fork() twice, then the parent calls exec()
D. Call fork() to create a child, then the child calls exec()

Solution

  1. Step 1: Understand process creation and replacement

    Calling exec() replaces the current process, so calling it directly stops the original program.
  2. Step 2: Use fork() then exec() in child

    By calling fork(), the program creates a child process. The child can then call exec() to run the new program, leaving the parent running.
  3. Final Answer:

    Call fork() to create a child, then the child calls exec() -> Option D
  4. Quick Check:

    fork() then exec() = safe new program run [OK]
Hint: fork first, then exec in child to keep parent alive [OK]
Common Mistakes:
  • Calling exec() directly and losing original process
  • Calling fork() twice unnecessarily
  • Calling exec() before fork()