CS506 Assignment 1 Solution (2025), Cheat Sheet of Web Design and Development

CS506 Assignment 1 Solution (2025), BScs 2025, Computer Scient, Virtual University of Pakistan

Typology: Cheat Sheet

2024/2025

Uploaded on 05/22/2025

muhammad-umer-ejaz
muhammad-umer-ejaz 🇵🇰

1 document

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
BC220410529
Muhammad Umer Ejaz
CS604 Assignment 01 Solution:
Part A Code:
#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) {
pf3
pf4
pf5

Partial preview of the text

Download CS506 Assignment 1 Solution (2025) and more Cheat Sheet Web Design and Development in PDF only on Docsity!

BC

Muhammad Umer Ejaz

CS604 Assignment 01 Solution:

Part A Code:

#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: