Operating Systems (CS604)
Assignment # 01
Spring 2025
BC230405620
Abdul Hannan
Solution:
Part A Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
// Function to calculate factorial
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
pid_t pid;
int i;
for (i = 1; i <= 3; i++) {
pid = fork(); // Create child process
if (pid < 0) {
perror("Fork failed");
exit(1);
}
if (pid == 0) {
// Child process code
int fact = factorial(i + 2); // Correctly calculating factorial of (i + 2)
printf("Child Process: PID = %d, PPID = %d\n", getpid(), getppid());
printf("Student ID: BC230405620, Name: Abdul Hannan\n");
printf("Factorial of %d is: %d\n\n", i + 2, fact);
fflush(stdout); // Ensure output is written
exit(0); // Exit child process
}
}
// Parent waits for all 3 children
for (i = 0; i < 3; i++) {
wait(NULL);
}
printf("Parent process: All child processes have completed.\n");
return 0;
}
Output Screenshot
Part B Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t child1, child2;
// Create first child process
child1 = fork();
if (child1 < 0) {
perror("Fork for Child 1 failed");
exit(1);
}
if (child1 == 0) {
// First child replaces process image with 'ls -l' command
printf("Child 1 (PID=%d, PPID=%d): Executing 'ls -l'\n", getpid(), getppid());
execlp("ls", "ls", "-l", NULL);
// If execlp fails
perror("execlp failed in Child 1");
exit(1);
}
// Create second child process
child2 = fork();
if (child2 < 0) {
perror("Fork for Child 2 failed");
exit(1);
}
if (child2 == 0) {
// Second child simply runs and exits
printf("Child 2 (PID=%d, PPID=%d): Running and exiting...\n", getpid(),
getppid());
exit(0);
}
// Parent process sleeps instead of using wait()
// This allows time to inspect zombie processes
printf("Parent (PID=%d): Sleeping for 30 seconds to observe zombie processes...\n",
getpid());
sleep(30);
// After sleep, parent exits
printf("Parent: Done sleeping. Exiting now.\n");
return 0;
}
Output Screenshot