Process Tree
🧠 Experiment: Process Creation Using fork() and Viewing the Process Tree
🎯 Aim:
To create a new process using the fork() system call, print the parent and child process IDs, and use the pstree command to observe the process tree starting from the init (systemd) process.
🧩 Theory:
-
The
fork()system call is used to create a new process. -
The newly created process is called the child process, and the original is the parent process.
-
After a successful
fork(), two processes run concurrently:-
Both execute the same code following the
fork() -
But they receive different return values:
-
0in the child process -
The child’s PID in the parent process
-
-
-
The init (or systemd) process is the ancestor of all processes in Linux.
The pstree command displays processes in a hierarchical tree format, showing parent–child relationships.
🧪 Step 1: Write the C Program
Create a file named fork_example.c:
🧪 Step 2: Compile and Run
🧾 Sample Output:
This shows that:
-
The parent has PID
3412 -
The child has PID
3413 -
The child’s parent PID matches the parent’s PID
🧪 Step 3: Observe the Process Tree
While the program is running (especially during the 5-second sleep), run in another terminal:
or, to view the entire tree from the init process:
🧾 Sample Output (Simplified):
Explanation:
-
systemd(1)is the init process (PID 1) -
bash(3200)is your shell (parent of your program) -
fork_example(3412)is the parent process created by you -
fork_example(3413)is the child process created byfork()
🧩 Step 4: Understanding Process Hierarchy
-
Every process (except init/systemd) is a child of another process.
-
The fork() system call duplicates the parent process.
-
Using
pstree, you can visualize this relationship easily.
🧩 Step 5: Verify with ps command
You can also verify the parent-child relationship using ps:
Sample Output:
This shows:
-
The child (3413) has parent 3412
-
The parent (3412) has parent 3200 (bash)
🧩 Step 6: After Process Termination
Once both processes finish, re-running pstree will no longer show them — they were temporary.
🧾 Summary Table
| Concept | Command / Output |
|---|---|
| Create process | fork() system call |
| Parent PID | getpid() |
| Child PID | Returned by fork() |
| Parent of child | getppid() |
| Show process tree | pstree -p |
| Show parent-child relationship | `ps -ef |
✅ Result:
-
A new process was successfully created using the
fork()system call. -
The parent and child PIDs were displayed.
-
The
pstreecommand was used to visualize the process hierarchy, confirming that both parent and child originate from the init (systemd) process.
🧠 Extension Exercise (for students):
Modify the program to:
-
Have the child execute another command using
execlp()(e.g.,ls). -
Observe the change in process tree.
-
Notice that the child replaces its code with the new program.
Comments
Post a Comment