



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
CS506 Assignment 1 Solution (2025), BScs 2025, Computer Scient, Virtual University of Pakistan
Typology: Cheat Sheet
1 / 6
This page cannot be seen from the preview
Don't miss anything!




Muhammad Umer Ejaz
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> int factorial(int n) { if (n == 0 || n == 1) return 1; return n * factorial(n - 1); } int main() { pid_t pid; int i, status; printf("Parent Process (PID: %d) started\n", getpid()); for (i = 0; i < 3; i++) { pid = fork(); if (pid < 0) { fprintf(stderr, "Fork failed for child %d\n", i+1); return 1; } else if (pid == 0) {
printf("\nChild %d Process:\n", i+1); printf("PID: %d, PPID: %d\n", getpid(), getppid()); printf("Student ID: BC220410529, Student Name:Muhammad Umer\n"); int num = i + 3; int result = factorial(num); printf("Factorial of %d is %d\n", num, result); return 0; } } for (i = 0; i < 3; i++) { wait(&status); } printf("\nParent Process Summary: All 3 child processes have completed.\n"); return 0; } Output Screen:
pid2 = fork(); if (pid2 == 0) { printf("Child 2 PID: %d, Parent PID: %d\n", getpid(), getppid()); printf("Child2 exiting...\n"); exit(0); } wait(NULL); wait(NULL); printf("Parent: Both children have terminated.\n"); return 0; } Output Screen: Part B Updated 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) { printf("Child 1 (execlp) PID: %d, Parent PID: %d\n", getpid(), getppid()); execlp("ls", "ls", "-l", NULL); perror("execlp failed"); exit(1); } pid2 = fork(); if (pid2 == 0) { printf("Child 2 PID: %d, Parent PID: %d\n", getpid(), getppid()); printf("Child2 exiting...\n"); exit(0); } // Parent process sleeps for 20 seconds (check with 'ps -l') printf("Parent PID: %d sleeping for 20 seconds (inspect with 'ps -l')...\n", getpid()); sleep(20); printf("Parent done sleeping..\n"); return 0; } Output Screen: