Back to the 2023 paper

Module 2: Processes & Scheduling

20237m

Write a program using "fork" to demonstrate the parent-child relationship of processes.

Worked SolutionAI Assisted

C program demonstrating fork parent-child

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
 pid_t p = fork();
 if(p < 0){ perror("fork"); return 1; }
 else if(p == 0){
   // Child
   printf("Child: PID=%d, PPID=%d
", getpid(), getppid());
   // child work
 } else {
   // Parent
   printf("Parent: PID=%d, Child PID=%d
", getpid(), p);
   wait(NULL); // wait for child
   printf("Parent: child finished
");
 }
 return 0;
}

Explanation: fork() duplicates process; returns 0 in child, child PID in parent, -1 on error. Parent and child execute concurrently with separate address spaces. wait() synchronizes. Demonstrates that after fork, both continue after fork statement.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.