Bird
Raised Fist0
Operating Systemsknowledge~10 mins

Process creation (fork and exec) in Operating Systems - Step-by-Step Execution

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
Concept Flow - Process creation (fork and exec)
Start: Running Process
Call fork()
Create Child Process
Child: Returns 0 from fork()
Call exec() to run new program
Replace Child's code with new program
Parent: Returns child's PID from fork()
Parent continues original program
The original process calls fork() to create a child. The child gets 0 return and can call exec() to run a new program. The parent gets child's ID and continues.
Execution Sample
Operating Systems
pid = fork()
if pid == 0:
    exec("/bin/ls")
else:
    wait()
This code creates a child process with fork. The child runs 'ls' using exec, the parent waits for child to finish.
Analysis Table
StepProcessActionfork() Returnexec() CalledResulting State
1ParentCalls fork()N/ANoParent running, fork called
2Parentfork() returns child's PIDChild PID (e.g. 1234)NoParent continues original code
2Childfork() returns 00NoChild starts execution
3ChildCalls exec("/bin/ls")0YesChild replaced by 'ls' program
4ParentCalls wait()Child PIDNoParent waits for child to finish
5ChildRuns 'ls' program0YesChild runs new program until exit
6Parentwait() returns after child exitsChild PIDNoParent resumes after child ends
💡 Execution stops when child finishes exec program and parent finishes wait.
State Tracker
VariableStartAfter fork()After exec()After wait()Final
pidundefined0 in child, child's PID in parent0 in child (exec replaces code, pid unchanged)child's PID in parentchild's PID in parent
Key Insights - 3 Insights
Why does fork() return 0 in the child but a positive number in the parent?
fork() returns 0 in the child process to indicate it is the new child. The parent gets the child's process ID (a positive number). See execution_table step 2.
What happens to the child's code after exec() is called?
exec() replaces the child's current program code with a new program. The child's process ID stays the same, but the code and data change. See execution_table step 3 and 5.
Why does the parent call wait() after fork()?
The parent calls wait() to pause and let the child finish its new program before continuing. This prevents the child from becoming a 'zombie' process. See execution_table step 4 and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2. What value does fork() return in the child process?
A-1
BChild's PID
C0
DUndefined
💡 Hint
Check the 'fork() Return' column for the child process at step 2.
At which step does the child's program get replaced by the new program?
AStep 3
BStep 1
CStep 5
DStep 6
💡 Hint
Look for when exec() is called in the 'exec() Called' column.
If the parent did not call wait(), what would happen according to the execution flow?
AParent would immediately exit before child finishes
BChild would become a zombie process
CParent would wait indefinitely
DChild would never run exec()
💡 Hint
Refer to key_moments about why wait() is important to prevent zombie processes.
Concept Snapshot
fork() creates a new child process by duplicating the parent.
In the child, fork() returns 0; in the parent, it returns child's PID.
exec() replaces the child's code with a new program.
Parent can call wait() to pause until child finishes.
This sequence creates a new process running a different program.
Full Transcript
Process creation in operating systems often uses fork and exec. First, a running process calls fork(), which creates a new child process. The fork call returns 0 in the child and the child's process ID in the parent. The child can then call exec() to replace its program with a new one, such as running a different command. Meanwhile, the parent can call wait() to pause until the child finishes. This method allows one process to create another and run a different program, managing execution order and resources.

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()