📝 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.
📝 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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()?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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?
📖 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()?
📖 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?
📖 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.