(4) Write a c program to represent wait() sytem call Waiting for All Children
Here's a C program that demonstrates using the wait() system call to wait for all
child processes before the parent resumes execution.
Explanation:
The parent process creates multiple child processes using fork().
Each child process prints a message and sleeps for a random time to simulate
work.
The parent waits for each child using wait() in a loop, ensuring that all child
processes finish before it continues execution.
C Program: Using wait() to Wait for All Children
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define NUM_CHILDREN 3 // Define the number of child processes
int main() {
pid_t pids[NUM_CHILDREN];
// Creating multiple child processes
for (int i = 0; i < NUM_CHILDREN; i++) {
pids[i] = fork();
if (pids[i] < 0) {
perror("Fork failed");
exit(1);
} else if (pids[i] == 0) {
// Child process
printf("Child %d (PID: %d) is running...\n", i + 1, getpid());
sleep(2 + i); // Simulate work (different sleep times)
printf("Child %d (PID: %d) is exiting.\n", i + 1, getpid());
exit(0);
}
}
// Parent process waits for all child processes
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(NULL); // Wait for any child to terminate
printf("Parent: A child process has terminated.\n");
}
printf("Parent process (PID: %d) has waited for all children. Exiting.\n",
getpid());
return 0;
}
Example Output
Child 1 (PID: 1235) is running...
Child 2 (PID: 1236) is running...
Child 3 (PID: 1237) is running...
Child 1 (PID: 1235) is exiting.
Parent: A child process has terminated.
Child 2 (PID: 1236) is exiting.
Parent: A child process has terminated.
Child 3 (PID: 1237) is exiting.
Parent: A child process has terminated.
Parent process (PID: 1234) has waited for all children. Exiting.
Key Takeaways:
Creates multiple child processes using fork().
Each child performs some work (sleep() simulates workload).
Parent waits for all children using wait() in a loop.
Prevents zombie processes by ensuring all child processes are reaped.