Process creation and executing another process
🎯 Aim:
-
To write a program that adds two integers provided via the command line and compile it to an executable named
myadder. -
To write another program that uses
fork()to create a child process and make the child process execute themyadderprogram usingexecvp().
🧩 Theory:
-
The
fork()system call creates a new process (a child) by duplicating the calling process. -
The
exec()family of functions replaces the current process image with a new program. -
execvp()searches for the program in thePATHand executes it with given arguments. -
When a child process calls
execvp(), its memory image is replaced with that of the new program — meaning the child becomes the new program (myadderin this case).
🧪 Step 1: Program 1 — myadder.c
This program reads two integers from the command line, adds them, and prints the result.
🧩 Compile and Test
Output:
✅ myadder is ready.
🧪 Step 2: Program 2 — fork_exec.c
This program creates a child process using fork().
The child process executes the myadder program using execvp().
🧩 Compile and Run
🧾 Sample Output:
🧩 Step 3: Explanation
| Concept | Description |
|---|---|
fork() | Creates a child process. Both parent and child continue execution. |
pid == 0 | Indicates the child process. |
execvp() | Replaces the child’s process image with another executable (myadder). |
wait() | Makes the parent wait until the child finishes. |
After execvp():
-
The child process stops executing fork_exec.c code.
-
It becomes the myadder process.
-
Once
myaddercompletes, the child terminates, and the parent resumes.
🧩 Step 4: Verify Process Replacement
While running fork_exec, observe the process list using another terminal:
You’ll see something like:
➡️ This confirms that the child process has been replaced by the myadder image.
🧩 Step 5: Observe Using pstree
Run pstree to visualize the process hierarchy:
Example Output:
This shows:
-
fork_execcreated a child process -
The child was replaced by the myadder program
🧾 Summary Table
| Step | Operation | Function/Command | Observation |
|---|---|---|---|
| 1 | Create process | fork() | Child and parent created |
| 2 | Replace process image | execvp() | Child replaced with myadder |
| 3 | Synchronization | wait() | Parent waits for child |
| 4 | Verify tree | pstree | Visual process hierarchy |
✅ Result:
-
A child process was successfully created using
fork(). -
The child process was replaced with the
myadderexecutable usingexecvp(). -
The parent process waited until the child finished execution.
-
Verified using
pstreethat the child process becamemyadder.
🧠 Extension Exercise (Optional for Students):
Modify fork_exec.c so that the user enters two integers, and the child passes them to myadder dynamically using execvp() arguments.
Comments
Post a Comment