Write a program in c (using fork( ) and/or exec( ) commands) where parent and child execute:
a) Same program, same code.
b) Same program, different code.
c) before terminating, the parent waits for the child to finish its task.
Below is the C program that solves the given problems using fork() and exec() system calls:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
// Forking a new process
pid = fork();
if (pid < 0) {
// Fork failed
perror("Fork failed");
return 1;
}
if (pid == 0) {
// Child process
printf("Child: I am the child process.\n");
// Part b: Same program, different code (Exec called in child)
char *args[] = {"/bin/echo", "Hello from child!", NULL};
execvp(args[0], args);
perror("Exec failed"); // execvp only returns if it fails
} else {
// Parent process
printf("Parent: I am the parent process.\n");
// Part a: Same program, same code (Parent and child do the same thing)
wait(NULL); // Parent waits for the child to finish
printf("Parent: Child process has finished.\n");
// Part c: Ensure parent waits for child process before terminating
}
return 0;
}