🎓 BookMCQ
← Back to 4. Threads in Operating System

📝 Fork and exec system calls in multithreading (33 MCQs)

Process Creation and Image Replacement in Multithreaded Programs

fork() and exec() are process-control system calls commonly used in Unix-like operating systems. fork() creates a child process, while exec-family functions replace the calling process image with a new program. Their behaviour requires special consideration in multithreaded applications because fork() creates a child containing only the calling thread, whereas exec() replaces the entire process image.

Why Forking a Multithreaded Process Creates Difficulties

A multithreaded process may contain shared locks, runtime state, and resources managed by several threads. After fork(), the child contains only the thread that invoked the call, but its copied memory may retain lock states established by threads that no longer exist in the child. This can cause deadlocks if the child uses affected facilities before exec().

Child Thread State and Exec Image Replacement

When one thread calls fork(), the kernel creates a child process with a single surviving thread corresponding to the caller. The child receives a copy-on-write view of the parent's address space. If it calls an exec-family function, the current program image is replaced, and the new program starts with a fresh process image and its initial execution thread.

Forking from One of Three Running Threads

Suppose a process contains threads T1, T2, and T3, and T2 calls fork(). The parent continues with all three threads, but the child initially contains only the thread corresponding to T2. If the child calls exec(), its previous program image and thread state are replaced by the new executable.

Lock Safety, Runtime Consistency, and Process Creation Costs

These operations support command execution and process creation in multithreaded applications, especially shell and server workflows. However, inherited lock states and library internals complicate child-side activity. POSIX imposes strict restrictions on functions safely called between fork() and exec() in a multithreaded process; applications commonly perform only necessary safe operations before executing the new program.

Misconceptions About fork and exec Behaviour

'fork() duplicates every parent thread in the child' is incorrect because only the calling thread survives in the child. 'exec() creates an additional child process' is incorrect because it replaces the calling process image. 'The parent loses its other threads after fork()' is incorrect because the parent's threads continue independently.

Exam Focus: Thread Counts Before and After fork and exec

Given a process with several threads, identify how many remain in the parent and child after fork(). Explain the effect of exec() on the child process image and thread state. Questions may examine copy-on-write memory, inherited locks, POSIX async-signal-safe restrictions, and why a multithreaded child normally calls exec() promptly.

Key Terms of fork and exec in Multithreading

  • fork() - Creates a child process.
  • exec() - Replaces the process image.
  • Calling thread - Thread invoking fork().
  • Copy-on-write - Delayed copying of memory pages.
  • Child process - New process created by fork().
  • Deadlock - Indefinite waiting for unavailable resources.
11
Easy
11
Medium
11
Hard

📝 All Fork and exec system calls in multithreading MCQs

Q1. A multithreaded server must launch an external utility while continuing to serve requests in its existing process. Which sequence is appropriate?

A.Call fork, then call an exec-family function in the child ✅
B.Call exec in the service process and then fork
C.Create a user thread and assume it has a new process identity
D.Call wait before creating the child
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: fork() creates a separate child process, and an exec-family call replaces that child's program image. The parent retains its own execution and can continue serving requests while the external utility runs independently.

Q2. A chart records parent-thread count at fork and child-thread count immediately afterward on a POSIX system: (1,1) ; (2,1) ; (4,1) ; (8,1) ; (12,1). Which pattern does the chart show?

A.The child duplicates every parent thread
B.The child contains no thread until exec
C.The child contains only the calling thread regardless of the parent's thread count ✅
D.The child always contains the main thread only
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: The measured child-thread count remains one as the parent's thread count rises from one to twelve. POSIX fork creates the child with only the thread that called fork, not copies of all parent threads.

Q3. After fork() in a multithreaded program, which statement describes the parent's threads?

A.All parent threads except the caller terminate
B.The parent continues with its existing threads ✅
C.The parent is reduced to one thread
D.The parent is replaced by the child executable
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: fork() creates a separate child without removing the parent's other threads. The parent continues with its existing multithreaded state, while the child contains only the calling thread and an inherited view of process memory.

Q4. A child created by fork() immediately calls execve() successfully. What happens to its previous program image?

A.It runs alongside the new image
B.It is copied into another child
C.Only its heap is replaced while old threads continue
D.The old image is replaced by the new executable image ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: A successful execve() replaces the calling process image, including its code, data, and stack. The process continues under the new program, and the old program's execution state is not resumed alongside it.

Q5. A developer assumes fork() duplicates every parent thread into the child. Which correction is accurate?

A.The child contains only the calling thread, while its address space is inherited ✅
B.The child contains only the main thread regardless of who called fork
C.The child contains all threads but suspends them
D.fork() is forbidden whenever a process has multiple threads
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: POSIX fork semantics create a child with one thread: the caller. The child inherits process memory state, commonly through copy-on-write, but the other parent threads do not continue as child threads.

Q6. A process has threads T1, T2, and T3. T2 calls fork(), and the child then calls exec() successfully. Which state remains in the parent?

A.Only T2 remains
B.The parent loses T1 and T3
C.T1, T2, and T3 continue in the parent ✅
D.The parent is replaced by the new executable
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: The fork operation creates a separate child and does not remove the parent's other threads. A later exec in the child replaces only the child's image, leaving the parent process and its three threads intact.

Q7. A program calls execve() with a path that does not identify a loadable executable. What should the child code normally expect?

A.The process image is replaced with an empty image
B.execve() returns an error and the child continues after the call ✅
C.The parent automatically executes the requested program
D.The child is always terminated by the kernel before returning
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: If execve() cannot load the requested program, it returns -1 and sets errno in the calling process. The old image remains active, so the child must handle the failure rather than assuming replacement occurred.

Q8. A developer wants a child to redirect standard output to a file before launching a utility. Which sequence is appropriate?

A.Call exec in the parent, then change the child's file descriptors
B.Call wait before opening the output file
C.Create a thread and redirect only that thread's stack
D.Fork, configure the child's file descriptors, then exec the utility ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: A common launch sequence creates a child with fork(), adjusts the child's descriptors using operations such as dup2(), and then calls exec(). The parent retains its own descriptors and process image unless deliberately changed.

Q9. A child created by fork() writes to a global variable, but the parent does not observe that update. Why?

A.Parent and child have separate logical address spaces after fork ✅
B.Global variables are not inherited by fork
C.The child writes directly into the parent's stack
D.fork() automatically converts globals into thread-local variables
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: After fork(), parent and child have separate logical address spaces, even when copy-on-write initially shares physical pages. A child write changes its own memory view and is not automatically propagated to the parent.

Q10. A controlled copy-on-write experiment records distinct shared pages first written by the child and private page copies created: (0,0) ; (1,1) ; (2,2) ; (4,4) ; (8,8). Assume each write targets a previously shared page. Which relationship is shown?

A.One private copy is created per distinct shared page first written ✅
B.Every page is copied before fork returns
C.The parent and child continue using one writable page after every write
D.Private copies are created only when the parent writes
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: Under the stated assumption, each first write to a distinct shared page causes one private copy. The chart shows equal counts, illustrating how copy-on-write delays copying until modification rather than duplicating every page immediately.

Q11. A parent and child alternate reads through inherited descriptors. The log records completed reads and shared file offset: (1,4) ; (2,8) ; (3,12) ; (4,16) ; (5,20), with each read consuming four bytes. What does the pattern support?

A.Each process has an unrelated independent offset
B.The child receives a private copy of the file contents
C.The descriptors can refer to one open file description with a shared offset ✅
D.Only the parent can advance the file offset
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: The offset advances by four bytes after each combined read, reaching twenty after five reads. This is consistent with inherited descriptors referring to the same open file description and therefore sharing its file position.

Q12. A multithreaded process forks while another parent thread holds a mutex. The child later tries to acquire that mutex. What can happen?

A.The mutex is automatically unlocked in the child
B.The owning parent thread is copied to release it
C.The mutex is converted into a semaphore
D.The child can deadlock because the lock remains held by a thread that does not exist there ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The child inherits memory containing the mutex state but only one thread survives. If a vanished thread held the mutex, the child may see it as locked with no thread available to release it, causing deadlock.

Q13. After fork() in a multithreaded POSIX process, what restriction applies to the child before it successfully calls execve()?

A.It may safely call only async-signal-safe functions ✅
B.It may call any library function because memory was copied
C.It must create replacement copies of all parent threads
D.It may perform arbitrary allocation if no other process is running
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: POSIX restricts the multithreaded child to async-signal-safe operations until an exec function succeeds. Other library routines may rely on locks or runtime state inherited from threads that no longer exist in the child.

Q14. A child process calls printf() after fork() in a multithreaded application and occasionally deadlocks. What is a plausible explanation?

A.printf() always waits for the parent to terminate
B.The child shares the parent's instruction pointer
C.A library lock may have been held by a parent thread that was not copied into the child ✅
D.printf() automatically performs exec() internally
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Buffered I/O libraries may use internal locks. If a vanished parent thread held such a lock at fork time, the child can inherit a locked state and deadlock when printf() attempts to acquire it.

Q15. A multithreaded application must launch another program but needs substantial setup logic. Which alternative can reduce post-fork hazards on supported systems?

A.Fork repeatedly until the child has no inherited locks
B.Use an appropriate spawn API with supported process-launch actions ✅
C.Run the external executable inside the parent's current address space
D.Create another thread in the child before calling exec
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: A supported spawn API can combine process creation with program launch and configured actions. It may avoid extensive application code in the fragile post-fork child interval, although available semantics vary across platforms.

Q16. A program forks while a parent thread has buffered output that has not yet been flushed. Both parent and child later flush their inherited buffers. What can occur?

A.The child automatically removes the parent's buffer
B.The output is guaranteed to appear once
C.fork() clears all user-space output buffers
D.The same buffered text may be emitted more than once ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The child inherits the memory state containing buffered output. If both processes later flush copies of that buffer, duplicated text may appear; flushing before fork or avoiding child-side buffered I/O can prevent this problem.

Q17. A child calls exec() successfully. What happens to its old thread-local variables?

A.The old program's thread-local execution state is replaced; the new program initializes its own state ✅
B.All thread-local values become shared with the parent
C.Every old thread-local value is copied into the new executable
D.The old values become permanent environment variables
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Successful exec replaces the old program image and does not continue its former thread execution. The new program establishes its own runtime and thread-local storage, so it should not rely on old thread-local values surviving.

Q18. A multithreaded service forks a child and performs malloc() extensively before exec(). Why is this risky?

A.malloc() always creates another process
B.The child automatically receives every allocator helper thread
C.Allocator locks or runtime state may have been held by threads absent from the child ✅
D.Memory allocation is prohibited in every single-threaded process
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: An allocator may maintain internal locks and shared runtime state. After a multithreaded fork, the child lacks other threads that may have held those locks, so allocation before exec can deadlock or behave unpredictably.

Q19. A child executes an external program, but the parent needs to know whether exec failed and later obtain the child's exit status. Which design is appropriate?

A.Assume the parent's global variables are updated by the child
B.Use a pipe or another channel for launch errors, and wait or waitpid for termination status ✅
C.Call exec in the parent and inspect its return value later
D.Use the child's thread identifier as its exit status
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: An exec failure is observed in the child because exec runs there; the parent does not receive that return directly. A pipe can report launch errors, while wait or waitpid collects the child's eventual termination status.

Q20. A developer calls fork() and then exec() in the child, assuming successful exec returns to the old child code. Which correction is accurate?

A.exec returns zero after the new program finishes
B.exec starts a new thread but preserves the old image
C.exec waits for the parent before loading the executable
D.A successful exec does not return to the old program image ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: A successful exec replaces the current process image and begins the new program, so control does not return to the old code. If an exec-family call returns, it indicates failure and should be handled accordingly.

Q21. A process calls fork() while containing 3 threads. The child calls exec() successfully. How many threads does the new program initially have at its process entry?

A.One initial thread ✅
B.Three inherited threads
C.Zero threads until another fork
D.Four threads including the parent
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: The child created by fork initially contains only the calling thread. Successful exec replaces that program image and starts the new program with its initial execution thread; the other threads from the old image do not survive.

Q22. A process forks, and the child changes an element in a large global array. The parent continues reading its own array. Which statement best describes the memory relationship?

A.The parent's array is automatically updated by the child
B.Both processes must use one physical writable array permanently
C.The logical arrays are independent; copy-on-write may defer physical copying until modification ✅
D.The child cannot write global arrays after fork
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: Fork gives the child a logically separate memory image. Copy-on-write can share physical pages initially, but a child modification causes a private copy as needed, leaving the parent's corresponding array unchanged.

Q23. A multithreaded application wants the child to use a pipe for standard output when launching an external command. Which detail must be handled?

A.Exec automatically closes every descriptor inherited from the parent
B.The child should duplicate the desired pipe end onto standard output and close unneeded descriptors ✅
C.The parent must move its entire address space into the pipe
D.The child must create all parent threads before redirecting output
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The child can use descriptor operations such as dup2() to map the pipe's write end onto standard output, then close unneeded descriptors before exec. Inherited descriptors otherwise may keep pipe ends open unexpectedly.

Q24. A parent waits for a child using waitpid() after launching an external utility. What does waitpid() provide?

A.It replaces the parent's executable image
B.It creates a second child containing all parent threads
C.It guarantees the child used copy-on-write
D.It waits for a specified child and can collect its termination status ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: waitpid() lets the parent wait for a selected child and obtain its termination information. It does not launch the program or replace the parent's image; it is used to coordinate with a child process after creation.

Q25. A child terminates after exec(), but the parent never collects its termination status. What condition can result?

A.A zombie process entry may remain until the status is collected ✅
B.The child restarts with its previous thread set
C.The parent's threads are all converted into zombies
D.The child continues executing after termination
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: A terminated child whose status has not been collected may remain as a zombie, retaining a process-table entry. The parent should wait or use an appropriate child-reaping strategy to release that entry.

Q26. A child calls execve() successfully after fork(). Which statement about caught signal dispositions is generally correct under POSIX rules?

A.Every caught handler is copied into the new executable unchanged
B.All signals become pending simultaneously
C.Caught signal dispositions are generally reset to their default actions ✅
D.exec() converts signal handlers into kernel threads
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: Successful exec changes the process image, and caught signal dispositions are generally reset to default under POSIX rules. Signal masks and other signal attributes have separate rules, so applications should not assume every signal setting behaves identically.

Q27. A server launches an untrusted external utility using fork() and exec(). Which preparation is important for limiting unintended access?

A.Pass every parent environment variable and open descriptor without review
B.Carefully manage inherited descriptors, credentials, environment, and executable arguments ✅
C.Assume exec automatically drops every privilege and closes every descriptor
D.Share the server's writable heap with the utility
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Exec replaces program memory but does not automatically remove every inherited resource or privilege. Closing unnecessary descriptors, controlling credentials and environment, and constructing arguments deliberately reduce unintended access by the launched utility.

Q28. A child calls execve(), which fails, then calls exit() in a multithreaded program with inherited buffered streams and cleanup handlers. What is often safer for the minimal failure path?

A.Call every inherited cleanup handler and flush all buffers
B.Fork again to reset the stream state
C.Return from the start routine as though the child were a thread
D.Use _exit() when appropriate to avoid inherited user-space cleanup and duplicated buffer flushing ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: After fork, buffered streams and cleanup handlers may reflect parent state that should not run again in the child. If exec fails, _exit() can terminate without invoking inherited user-space cleanup routines or flushing duplicated buffers.

Q29. A multithreaded application needs a child with a consistent snapshot of two related structures updated by different threads. What should it do?

A.Coordinate updates and fork at a safe point, or use a suitable alternative process-launch design ✅
B.Assume fork makes every multi-step update atomic
C.Allow all threads to modify both structures during fork
D.Call exec before initializing either structure
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: Fork captures process memory but does not make a sequence of application updates atomic. Coordinating relevant state before fork or using a suitable launch mechanism helps prevent the child from inheriting a logically inconsistent snapshot.

Q30. A program uses fork() in a multithreaded process, then the child calls a complex logging library before exec(). Which design change best follows POSIX safety guidance?

A.Increase the number of child threads before logging
B.Use only necessary async-signal-safe operations in the child and proceed promptly to exec ✅
C.Call every parent thread's logging function from the child
D.Assume the library's internal locks are always reset by fork
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The post-fork child contains only the calling thread, while copied library state may include locks held by vanished threads. Restricting the child path to async-signal-safe operations until exec avoids many deadlock hazards.

Q31. A child inherits a pipe's write-end descriptor, then successfully calls exec(). The parent closes its own write end but never receives EOF. What is a likely explanation?

A.Exec always converts pipes into regular files
B.The child must be running several threads
C.The pipe data has been copied into the child's heap
D.The executed program still holds an inherited write-end descriptor, preventing EOF ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: A pipe reader sees EOF only after every write-end descriptor referring to that pipe is closed. If the executed program inherits an open writer, the pipe remains open; close-on-exec or explicit closure can prevent this.

Q32. A parent creates a child with fork() while it has four threads, then launches a utility in the child. Which statement about process identity is correct after successful exec()?

A.The child process generally retains its process ID while its program image changes ✅
B.The child becomes a thread of the parent
C.The child inherits the parent's process ID and merges with it
D.The parent process ID is replaced by the executable path
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: Exec replaces the calling process image but does not create a new process. The child normally retains its process identifier while running the new program, whereas the parent's identity and execution continue separately.

Q33. A parent and child need to distinguish their return paths immediately after fork(). What does a successful fork() return in each process?

A.The child PID in both processes
B.Zero in the parent and the child PID in the child
C.The same positive PID in both processes
D.The child PID in the parent and zero in the child ✅
💡 Difficulty: hard | ✅ Correct: D

📖 Explanation: On success, fork() returns the child's process ID in the parent and zero in the child. A return value of -1 in the parent indicates failure, with no child created.

🔗 Related Topics (MCQs)