Name: Muhammad Hasaan Mirza
VUID: BC210201663
CS604 Assignment 1 Solution
Part a
Output
C Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
pid_t pid;
int i;
for (i = 0; i < 3; i++) {
pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(1);
}
else if (pid == 0) {
// Child process
int fact = factorial(i + 2);
printf("Child Process : PID = %d, PPID: %d\n", getpid(), getppid());
printf("Student ID: BC210201663, Name: Muhammad Hasaan Mirza\n");
printf("Factorial of %d is: %d\n\n", i + 2, fact);
exit(0);
}
}
// Parent waits for 3 children
for (i = 0; i < 3; i++) {
wait(NULL);
}
printf("Parent: All child processes have completed.");
return 0;
}
Part b
Output
C Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
// First child
printf("Child 1: PID = %d, PPID = %d\n", getpid(), getppid());
printf("Child 1 exiting...\n");
exit(0);
}
pid2 = fork();
if (pid2 == 0) {
// Second child
printf("Child 2: PID = %d, PPID = %d\n", getpid(), getppid());
printf("Child 2 exiting...\n");
exit(0);
}
// Parent process
wait(NULL);
wait(NULL);
printf("Parent: Both children have terminated.");
return 0;
}
Part c
Output
C Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
// First child uses execlp
printf("Child 1: PID: %d, PPID: %d\n", getpid(), getppid());
execlp("ls", "ls", "-l", NULL);
// if execlp fails
perror("execlp failed");
exit(1);
}
pid2 = fork();
if (pid2 == 0) {
// Second child
printf("Child 2: PID = %d, PPID = %d\n", getpid(), getppid());
printf("Child 2 exiting...\n");
exit(0);
}
// Parent doesn't wait - sleep to allow zombie process to appear
printf("Parent sleeping for 10 seconds ...\n");
sleep(10);
printf("Parent: Done sleeping. Use 'ps -l' to check for zombie process.\n");
return 0;
}