(2) Write a c program to represent waitpid() system call for a Specific Child
Here's a C program demonstrating the waitpid() system call, which allows a parent
process to wait for a specific child process to terminate.
Explanation:
The fork() system call creates two child processes.
The parent process uses waitpid() to wait for a specific child (e.g., the
second child).
The waitpid() function provides finer control over which child process to
wait for compared to wait(), which waits for any child.
C Program using waitpid()
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
// Create first child process
pid1 = fork();
if (pid1 < 0) {
perror("Fork failed");
exit(1);
} else if (pid1 == 0) {
// First child process
printf("First child process (PID: %d) is running...\n", getpid());
sleep(3); // Simulate some work
printf("First child process (PID: %d) is exiting.\n", getpid());
exit(0);
}
// Create second child process
pid2 = fork();
if (pid2 < 0) {
perror("Fork failed");
exit(1);
} else if (pid2 == 0) {
// Second child process
printf("Second child process (PID: %d) is running...\n", getpid());
sleep(1); // Simulate some work
printf("Second child process (PID: %d) is exiting.\n", getpid());
exit(0);
}
// Parent process waits for the second child first
printf("Parent process (PID: %d) waiting for second child (PID: %d)...\n",
getpid(), pid2);
waitpid(pid2, NULL, 0);
printf("Parent process detected second child (PID: %d) termination.\n",
pid2);
// Parent process waits for the first child
printf("Parent process waiting for first child (PID: %d)...\n", pid1);
waitpid(pid1, NULL, 0);
printf("Parent process detected first child (PID: %d) termination.\n",
pid1);
return 0;
}
Example Output
Parent process (PID: 1000) waiting for second child (PID: 1002)...
First child process (PID: 1001) is running...
Second child process (PID: 1002) is running...
Second child process (PID: 1002) is exiting.
Parent process detected second child (PID: 1002) termination.
Parent process waiting for first child (PID: 1001)...
First child process (PID: 1001) is exiting.
Parent process detected first child (PID: 1001) termination.
Key Points:
fork(): Creates two child processes.
waitpid(pid, NULL, 0): Parent waits for a specific child (here, pid2 first).
Order Control: Unlike wait(), waitpid() allows the parent to decide which
child to wait for first.
sleep() Usage: Simulates some work for different child termination times.