🎓 BookMCQ
← Back to 18. The Linux System

📝 The fork() and exec() process model (36 MCQs)

Creating and Replacing Processes in Linux

Linux uses the fork() and exec() system call family to create and run processes. fork() creates a child process based on the calling process, while an exec function replaces the current process image with a new program. Together, they form a common process-launching model used by shells, service managers, and applications that start other programs.

Why Process Creation and Program Loading Are Separate

Separating process creation from program replacement provides flexibility. A child can inherit selected resources, change its execution environment, redirect input or output, and then run a different executable. Combining these actions into one fixed operation would make pipelines, command interpreters, and complex process setup less flexible.

Copy on Write and the execve Transition

After fork(), parent and child initially have separate process identities but share memory pages through copy-on-write mappings. A write causes the affected page to be copied when necessary. An exec function invokes the execve mechanism, which replaces the process's address space with the new program while retaining its process identity.

Example of a Shell Starting a Command

A shell calls fork() to create a child. The child configures its file descriptors and calls execve() to run ls. The parent may call waitpid() to collect the child's termination status. The child normally retains its PID across successful execve(), but its program code and memory image are replaced.

Efficiency, Inheritance and Process Control

Copy-on-write reduces the cost of creating a child that soon executes another program. File descriptors are normally inherited across fork(), while descriptors marked close-on-exec are closed during exec. Signal dispositions and other process attributes have specific inheritance rules, so not every parent property is copied unchanged.

Misconceptions About fork() and exec()

'exec() creates a new process with a new PID' is false because it replaces the current process image. 'fork() immediately copies every memory page' ignores copy-on-write. 'The parent always waits after fork()' is incorrect because waiting is a separate operation, commonly performed with wait or waitpid.

Exam Focus: Process Creation and Program Replacement

Trace parent and child execution after fork(), including its return values of zero in the child and the child's PID in the parent. Explain copy-on-write and follow a successful execve(). Questions may examine PID preservation, file descriptor inheritance, waitpid(), and process termination status.

Key Terms of the Linux Process Model

  • fork() - Creates a child process.
  • execve() - Replaces the current process image.
  • Copy on write - Copies shared pages when modified.
  • PID - Process identifier.
  • waitpid() - Collects a child's termination status.
8
Easy
17
Medium
11
Hard

📝 All The fork() and exec() process model MCQs

Q1. What is the primary purpose of the fork() system call in a UNIX‑like operating system?

A.It creates a new process that is a copy of the calling process ✅
B.It replaces the current process image with a new program
C.It terminates the calling process and returns its exit status
D.It changes the effective user ID of the process
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: Fork() is designed to duplicate the calling process, producing a child process that initially shares the same code, data, and open file descriptors. This behavior lets the parent continue running while the child can diverge later. The other options describe exec(), exit(), or setuid(), which are distinct system calls. Understanding fork() is essential for building multitasking applications such as shells or servers.

Q2. Why does UNIX separate process creation (fork) from program execution (exec) into two distinct system calls?

A.Because it allows a program to create a child and then modify the child’s environment before loading a new program
B.Because it simplifies the kernel by avoiding the need to load binaries directly
C.Because it reduces the number of system calls required to start a new program ✅
D.Because it enforces security by preventing a parent from directly executing code in its address space
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Separating fork and exec gives developers flexibility: after fork, the child inherits the parent’s environment and can change variables, file descriptors, or resource limits before exec loads a new binary. This two‑step model avoids having to specify the entire execution context in a single call. The other answers either misstate the purpose or ignore the advantage of preparatory modifications.

Q3. How does the address space of a child process immediately after a successful fork() compare to that of the parent before any exec()?

A.It is an exact copy, but the kernel uses copy‑on‑write so pages are shared until written
B.It is a completely new empty address space ✅
C.It contains only the kernel’s code and no user‑level data
D.It is identical, but the child receives a separate set of physical memory pages right away
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: When fork() succeeds, the child receives a virtual address space that appears identical to the parent’s, but modern kernels implement copy‑on‑write: physical pages are shared until either process writes to them. This optimization saves memory while preserving the illusion of a full copy. The other options describe behaviors that would either waste resources (full copy) or be impossible (empty or kernel‑only space).

Q4. A parent process wants to run a new program with a modified environment variable. Which sequence of system calls correctly achieves this?

A.exec() followed by setenv() in the parent
B.fork() then setenv() in the child, then exec() in the child
C.fork() only, letting the child inherit the original environment
D.exec() only, letting the kernel handle the environment change ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The correct approach is to fork, adjust the environment in the child with setenv(), and then exec the new program from that child. This ensures the parent’s environment remains unchanged. Option D describes that exact sequence: fork → setenv in child → exec in child. The other choices either modify the parent’s environment, omit the exec step, or skip the necessary fork, leading to incorrect behavior.

Q5. A simple web server forks a child process for each incoming client connection. Which statement best describes the memory impact of this design on modern UNIX systems?

A.Each child receives a completely independent copy of the server’s memory, doubling RAM usage per connection
B.The kernel uses copy‑on‑write, so pages are shared until a child modifies them, reducing overhead ✅
C.Forking creates threads that share all memory, so no extra memory is used
D.Memory usage is unrelated to fork; it depends solely on the size of the client request
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Modern kernels implement copy‑on‑write for forked processes, meaning the child initially shares the parent’s pages. Only when a child writes to a page does the kernel allocate a separate copy, which greatly reduces the memory cost of handling many connections. The other statements either ignore copy‑on‑write, confuse processes with threads, or claim no impact, which is inaccurate.

Q6. A parent process forks a child that immediately execs a different binary. The parent needs to wait for the child to finish and retrieve its exit status. Which combination of system calls should the parent use?

A.waitpid() after fork, and the child uses exec() ✅
B.exec() after fork, and the parent uses kill()
C.fork() followed by pause() in the parent
D.wait() before fork, and the child uses exit()
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: After fork, the child replaces its image with exec(), while the parent calls waitpid() (or wait()) to block until the child terminates and to obtain the status code. This pattern is the canonical way to synchronize a parent with a child that runs a new program. Using kill() or pause() would not reliably capture the exit status, and waiting before fork is impossible because the child does not yet exist.

Q7. How does vfork() differ from fork() in terms of parent and child process behavior?

A.vfork() creates a child that runs concurrently while the parent continues execution
B.vfork() suspends the parent until the child either calls exec() or exits
C.vfork() duplicates the entire address space like fork but without copy‑on‑write ✅
D.vfork() is identical to fork() except it always creates a new thread group
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: vfork() is a specialized version of fork that does not fully copy the address space; instead, it makes the child share the parent’s memory and suspends the parent until the child either execs a new program or calls _exit(). This avoids the overhead of copying pages but requires careful use to prevent race conditions. The other options mischaracterize the relationship or describe unrelated behavior.

Q8. A shell script needs to run two commands simultaneously. Which fork‑based approach correctly achieves this?

A.Call fork() once, then exec() the first command in the child and the second command in the parent
B.Call fork() twice, exec() the first command in the first child and the second command in the second child, leaving the parent to wait
C.Call exec() for the first command, then fork() for the second command
D.Call fork() once, then have the child exec the first command while the parent execs the second command ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: The reliable way to run two commands in parallel is to fork a child; the child execs the first command, and the parent execs the second command (or vice versa). This leaves both processes executing independently. Forking twice and leaving the parent to wait would serialize execution, and exec before fork would replace the shell entirely, preventing the second command from starting.

Q9. What system call creates a new process that is an exact copy of the calling process?

A.fork() ✅
B.exec()
C.wait()
D.exit()
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: The fork() system call duplicates the calling process, producing a child that begins execution at the same point with identical memory contents. exec() replaces the current program image, wait() merely suspends the parent until a child changes state, and exit() terminates a process. Because fork() directly creates an identical copy, it is the mechanism used whenever a program needs a new process that starts with the same context as its parent.

Q10. Why is separating process creation (fork) from program execution (exec) considered a security advantage in UNIX-like systems?

A.Simplicity
B.Compatibility
C.Security ✅
D.Performance
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: Separating fork from exec lets a program establish a controlled environment before loading new code. The child can drop privileges, close sensitive descriptors, or change its user ID after fork but before exec, ensuring the new program runs with reduced rights. This two‑step model prevents a program from inadvertently inheriting unsafe resources, enhancing system security. Compatibility and performance are benefits, but the primary security gain comes from the ability to prepare a safe context prior to execution.

Q11. After a successful fork, how does the child’s address space relate to the parent’s?

A.Shared read‑only
B.Identical but independent (copy‑on‑write) ✅
C.Completely separate new allocation
D.Merged
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: When fork succeeds, the child receives a virtual memory layout that appears identical to the parent, but the pages are marked copy‑on‑write. Both processes share the same physical pages until one modifies a page, triggering a private copy. This strategy saves memory while keeping the address spaces logically independent. It is not a true read‑only sharing, nor a completely new allocation, and the spaces are not merged; they remain distinct yet efficiently shared until a write occurs.

Q12. A parent process needs to run a new program with modified environment variables. Which call sequence should it use?

A.exec then fork
B.fork only
C.exec only
D.fork then exec ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The parent should first call fork() to create a child that inherits the current environment. Inside the child, it can adjust environment variables as needed and then invoke exec() to replace its image with the new program. This order guarantees the new program starts with the modified environment. Directly calling exec() without forking would alter the parent, and calling fork only would not run the new program, so the fork‑then‑exec sequence is the correct approach.

Q13. A program must run the external command grep on a file and then continue processing after grep finishes. Which approach correctly uses fork and exec?

A.fork then exec in child, parent calls wait() ✅
B.exec directly in parent
C.fork only, no exec
D.spawn a thread to run grep
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: The proper method is to call fork() so the parent creates a child process. In the child, exec() replaces its image with the grep command, while the parent calls wait() to pause until the child terminates. This ensures grep runs independently, the parent does not replace its own code, and execution resumes only after grep finishes. Direct exec would replace the parent, fork only would not run grep, and threading would not involve exec at all.

Q14. If a parent forks a child but never calls wait(), what is the most likely state of the terminated child?

A.Child becomes zombie ✅
B.Child becomes orphan
C.Parent crashes
D.Child terminated
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: When the child exits, the kernel retains its exit status and other information until the parent retrieves it with wait(). If the parent never calls wait(), the child remains in the zombie state, consuming a slot in the process table. The child is not an orphan because the parent is still alive, nor does the parent crash, and the child is not fully terminated because its resources are still held for the parent to collect.

Q15. A server forks three child processes to handle connections and then immediately calls exec to run a different binary without waiting. What happens to the child processes?

A.Children become zombies and cannot be reaped ✅
B.Children continue running and are reaped by init
C.Children are terminated
D.Parent continues handling after exec
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: After the parent execs a new program, it retains the same PID and remains the parent of the previously forked children. Because the parent does not call wait() before or after exec, each child that later exits will enter the zombie state, holding its termination information. Without a wait call, the zombies cannot be reaped, leading to resource leakage until the parent eventually exits or a wait is performed.

Q16. When a process calls exec to load a new program, what happens to its open file descriptors by default?

A.All descriptors are closed automatically
B.Descriptors remain open unless marked close‑on‑exec
C.All descriptors are duplicated ✅
D.Descriptors are transferred to a child process only
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: By default, exec() leaves all open file descriptors unchanged, allowing the new program to continue using them. Only those descriptors that have the close‑on‑exec flag set (O_CLOEXEC) are automatically closed during the exec transition. This behavior enables programs to inherit necessary resources while giving developers control over which descriptors should be closed, unlike automatic closure or duplication, which do not reflect the standard exec semantics.

Q17. What is the main reason the UNIX design separates the creation of a process from the execution of a new program?

A.It reduces memory usage
B.It allows a parent to change the child's environment before running a new program ✅
C.It simplifies kernel code
D.It enables simultaneous execution of multiple binaries
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: The correct answer is B because separating fork and exec lets the parent adjust environment variables, file descriptors, or resource limits in the child before the new program starts. Option A is incorrect; memory usage is not the primary goal. Option C is partially true but not the main reason. Option D is unrelated to the design intent. By allowing modifications after fork, the system provides flexibility and safety, which is essential when launching programs with customized settings.

Q18. A developer writes a script that must run a program with a modified PATH variable without affecting the parent shell. Which sequence of system calls should the script use to achieve this safely?

A.fork(), modify environment in child, exec() ✅
B.exec() then fork()
C.modify parent environment, then exec()
D.fork() only, no exec()
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: The correct answer is A because the script should first call fork()fork() to create a child, then use setenv() or modify the PATH in the child, and finally call exec()exec() to run the desired program. This isolates the environment change from the parent shell. Option B runs exec before fork, which cannot affect the child. Option C modifies the parent’s environment directly, violating the requirement. Option D omits the exec step, so the program never starts. Using fork‑exec ensures the parent remains unchanged.

Q19. Which system call creates an exact copy of the calling process?

A.exec()
B.wait()
C.fork() ✅
D.exit()
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: The correct answer is C. The fork()fork() system call creates a duplicate of the calling process, preserving its address space, file descriptors, and execution state. Option A, exec(), replaces the current process image but does not create a new process. Option B, wait(), pauses a process until a child terminates; it does not create processes. Option D, exit(), terminates the calling process. Knowing that fork is the mechanism for process duplication is fundamental for any UNIX‑like system.

Q20. Process A calls fork()fork() and the child process calls exec()exec() to replace its image with /usr/bin/grep. If Process A wants the child to inherit a file descriptor for an open log file, what must it do before calling exec()exec()?

A.Close the descriptor before exec
B.Duplicate or ensure descriptor is not close‑on‑exec before exec ✅
C.Change the descriptor after exec
D.Create a new descriptor unrelated to the log file
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: The correct answer is B because the parent must duplicate the file descriptor using dup() or ensure the descriptor is marked close‑on‑exec false before calling exec()exec(). This way the descriptor remains open across the exec boundary. Option A suggests closing the descriptor, which would make it unavailable to the new program. Option C changes the descriptor after exec, which is too late. Option D creates a new descriptor unrelated to the log file. Preserving the descriptor allows the child to continue logging correctly after exec.

Q21. Why does the UNIX model permit a process to invoke exec()exec() without first calling fork()fork()?

A.It lets the same process replace its image with a new program ✅
B.It is required for security isolation
C.It reduces scheduling overhead
D.It enables parallel execution of programs
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: The correct answer is A. Allowing a process to call exec()exec() without a prior fork()fork() lets the same process replace its code with a new program, conserving the process identifier and resources while simplifying program replacement. Option B incorrectly claims it is required for security; exec alone can be safe. Option C suggests it reduces scheduling overhead, which is a minor side effect, not the core reason. Option D states it enables parallelism, which actually requires multiple processes. Thus, exec’s primary purpose is to overlay a new program in the existing process.

Q22. Consider the following code snippet: \n\npid = fork();\nif (pid == 0) {\n execve(\/usr/bin/worker\, args, env);\n}\n// parent continues\nWhich modification ensures the parent does not create a zombie after the child calls exec()exec()?

A.Call wait() before fork
B.Call sleep() after fork
C.Call waitpid() in parent after fork ✅
D.Do not wait for child
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: The correct answer is C because adding a call to waitpid() in the parent after the fork ensures the parent reaps the child’s termination status, preventing a zombie. Option A omits any waiting, so the zombie remains. Option B calls wait() before fork, which does nothing for the new child. Option D uses sleep() to delay, which does not reap the child and still leaves a zombie. Properly waiting for the child after exec is the standard technique to keep the process table clean.

Q23. How does the environment of a parent process influence the environment of a child process created with fork()fork()?

A.The child starts with an empty environment
B.The child shares the same environment block as the parent
C.The child receives only variables set after fork
D.The child receives a copy of the parent's environment at fork time ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: The correct answer is D because when a process calls fork()fork(), the child inherits a copy of the parent’s environment variables, file descriptors, and resource limits, providing an identical execution context at the moment of fork. Option A claims the child gets a fresh environment, which is false. Option B suggests the child shares the same environment block, which would cause unintended side effects. Option C states the child receives only the variables explicitly set after fork, which is inaccurate. Inheritance ensures continuity unless the child deliberately changes its environment.

Q24. A server program uses threads and processes. To launch a new worker that runs a different binary while preserving thread-specific data in the parent, which combination of calls is appropriate?

A.Create a new thread that runs the binary
B.fork() then exec() in child while parent keeps threads ✅
C.exec() in the parent process
D.Mix threads and exec in the same process without forking
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: The correct answer is B because the server should fork a new process, then have the child call exec()exec() to run the different binary while the parent retains its threads and thread‑specific data. Option A uses only threads, which cannot run a separate binary image. Option C calls exec in the parent, replacing the server itself. Option D mixes threading and exec incorrectly, leading to undefined behavior. Fork‑exec isolates the new worker, preserving the original process’s thread context and allowing independent execution of the new program.

Q25. Which system call creates a new process in UNIX-like operating systems?

A.fork() ✅
B.exec()
C.wait()
D.exit()
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: The fork() system call duplicates the calling process, allocating a new process control block and a unique PID for the child. Exec() replaces the current program image but does not create a new process, wait() only pauses a parent until a child ends, and exit() terminates a process. Because only fork() actually allocates a fresh process, it is the correct answer. Knowing this lets developers launch independent tasks by first forking a child process.

Q26. Why does UNIX separate process creation (fork) from program execution (exec) instead of combining them into a single call?

A.To reduce system call overhead
B.To allow a parent to continue running the same program after creating a child
C.To enable the child to modify its environment before loading a new program ✅
D.To simplify the kernel implementation
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: Separating fork and exec lets the child process adjust its environment—such as changing directories, setting file descriptors, or altering variables—before loading a new executable. If the two operations were combined, the child would have no chance to prepare its context, limiting flexibility. This design choice gives programmers fine‑grained control over how a new program starts, which is essential for many real‑world utilities.

Q27. A parent process wants to run /usr/bin/editor with a custom PATH variable without affecting itself. Which sequence of calls correctly accomplishes this?

A.fork(); execve(\/usr/bin/editor\, …); setenv(\PATH\, …);
B.fork(); setenv(\PATH\, …); execve(\/usr/bin/editor\, …); ✅
C.execve(\/usr/bin/editor\, …); fork();
D.setenv(\PATH\, …); fork(); execve(\/usr/bin/editor\, …);
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: First the parent calls fork() to create a child. Inside the child, setenv(\PATH\, …) changes the environment for that process alone. Then execve() replaces the child’s address space with the editor binary, preserving the modified PATH. The other options either modify the parent’s environment or invoke exec before the fork, which would affect the original process. Using this sequence isolates the custom PATH to the editor instance only.

Q28. After a successful exec() call, which statement about the process's address space is true?

A.The original code and data remain unchanged.
B.Only the stack is replaced, leaving text and data intact.
C.All memory mappings except those marked as shared are discarded.
D.The process retains its original PID and open file descriptors unchanged. ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: Exec() replaces the current program image but keeps the same PID, allowing the kernel to track the process consistently. Open file descriptors remain open unless they have the close‑on‑exec flag set, so they continue to be usable by the new program. The other statements are incorrect: exec discards the old code and data, not just the stack, and while shared mappings may survive, the key point is the unchanged PID and descriptor inheritance.

Q29. A program calls fork() and then immediately exits without calling wait(). What state does the child process enter after it finishes execution?

A.Zombie ✅
B.Orphan
C.Running
D.Stopped
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: When the child terminates, the kernel keeps an entry containing its exit status until the parent retrieves it with wait() or waitpid(). Because the parent never calls wait(), the child’s entry remains, and the process is said to be a zombie. An orphan occurs when the parent exits first, and a stopped state requires a signal like SIGSTOP. Recognizing the zombie state helps developers prevent resource leaks by ensuring the parent reaps terminated children.

Q30. How does Linux's threading model differ from the traditional UNIX process model described for fork and exec?

A.Linux threads share the same PID, while UNIX processes have distinct PIDs.
B.Linux implements threads as lightweight processes that share address space, unlike separate processes in UNIX. ✅
C.Linux does not support fork(), only clone().
D.Linux requires exec() to create a new thread.
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Linux creates threads using the clone() system call, allowing multiple threads to share the same address space, file descriptors, and other resources while each has its own thread ID. Traditional UNIX treats each forked process as a completely independent entity with its own memory and resources. The other options are inaccurate: threads have distinct TIDs, Linux still supports fork(), and exec() replaces a process image rather than creating threads.

Q31. Process P calls fork() producing child C1. Both P and C1 then each call fork() again, creating C2 and C3 respectively. All four processes subsequently call exec() to run different binaries: P runs A, C1 runs B, C2 runs C, and C3 runs D. Which process will have a PID that is a multiple of 4 if the first PID assigned was 1000?

A.Process running A ✅
B.Process running B
C.Process running C
D.Process running D
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: Assuming the kernel assigns successive PIDs, P receives 1000, C1 gets 1001, C2 receives 1002, and C3 gets 1003. The only PID that is evenly divisible by 4 among these is 1000, belonging to the original process P, which later execs program A. The other processes have PIDs that leave a remainder when divided by 4, so they do not meet the condition.

Q32. A server program wants to handle each client connection in parallel using fork(). Which code snippet correctly prevents the server from creating a zombie process after the child terminates?

A.After fork, parent calls exit().
B.Parent calls waitpid(-1, NULL, 0) inside an infinite loop. ✅
C.Child calls wait() before exiting.
D.Parent ignores SIGCHLD signal.
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Using waitpid(-1, NULL, 0) in a loop allows the parent to reap any terminated child, eliminating zombie entries. The other options either terminate the parent prematurely, make the child wait on itself (which never happens), or ignore SIGCHLD, which would still leave zombie processes until the parent explicitly waits. Properly reaping children ensures system resources are reclaimed and keeps the server stable under heavy load.

Q33. What is a primary security advantage of using exec() after a fork() when launching an untrusted program?

A.Exec() encrypts the program's code in memory.
B.Fork() isolates the untrusted code in a separate process with its own resources.
C.Exec() replaces the address space, discarding any inherited privileges. ✅
D.Fork() disables all system calls for the child.
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: Exec() overwrites the child's memory image with the new program, removing any previous code, data, and potentially lingering privileges. This clean slate reduces the chance that the untrusted program inherits sensitive information from the parent. While fork does provide isolation, the crucial security step is exec, which ensures the new program starts with only the resources explicitly allowed. The other statements are false: exec does not encrypt code, and fork does not disable system calls.

Q34. If fork() fails, it returns -1. Which error handling sequence correctly checks for failure of both fork() and exec() calls?

A.if (fork() == 0) { if (execve(... ) < 0) perror(\exec\); } else { perror(\fork\); }
B.pid = fork(); if (pid < 0) { perror(\fork\); exit(1); } if (pid == 0) { if (execve(... ) == -1) { perror(\exec\); exit(1); } } ✅
C.if (fork() > 0) { execve(...); } else { perror(\fork\); }
D.pid = fork(); if (pid == 0) { perror(\fork\); } else { if (execve(... ) == 0) { perror(\exec\); } }
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The correct pattern stores the fork result in pid, checks for a negative value to detect failure, and exits if fork fails. Inside the child branch (pid == 0), execve is called and its return value of -1 indicates an error, which is then reported and the child exits. The other snippets either misplace the error checks, treat successful exec as an error, or ignore the need to exit on failure, leading to undefined behavior.

Q35. In Linux, threads are created using the clone() system call, which can share various resources with the parent. Which combination of flags best mimics the traditional UNIX process behavior where each thread has its own memory space but shares file descriptors?

A.CLONE_VM | CLONE_FILES
B.CLONE_FILES ✅
C.CLONE_VM | CLONE_FS
D.CLONE_THREAD | CLONE_SIGHAND
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Using only CLONE_FILES tells the kernel to share the file descriptor table while keeping separate memory spaces, matching the UNIX model where processes have independent address spaces but can share open files. CLONE_VM would cause memory to be shared, which is not desired here. The other flag sets either share memory or thread group semantics, diverging from the intended behavior.

Q36. A script uses fork() to create a child that runs a computationally intensive task, while the parent waits for the child to finish and then prints \Done\. Which statement about CPU usage is true?

A.Both parent and child will use CPU simultaneously, doubling total usage.
B.The parent will consume CPU only while waiting, so total usage equals child's usage.
C.The child will run on a separate core, leaving the parent idle.
D.The operating system will schedule the parent and child on the same core, but only one runs at a time. ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: When both processes are runnable, the scheduler may place them on different cores if available, but even on a single core they are time‑sliced, meaning only one executes at any instant. The parent, while waiting, typically blocks in a wait system call and uses negligible CPU, so most CPU time is spent in the child. Therefore, the OS ensures efficient use without both consuming CPU simultaneously, matching option D.}

🔗 Related Topics (MCQs)