OS Assignment 1 (Daniyal Aqil 193 (E) )

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

OS (Lab)

Operating System

Name : Daniyal Aqil


Roll No: 193/BSCS/5th Sem
Section : E
Submitted To : Usama Asif
Question No # 1

Write a program using fork() system call to create two child of the same
process i.e., Parent P having child process P1 and P2.

#include <stdio.h>
#include <unistd.h>
#include <types.h>

int main() {
pid_t pid1, pid2;

pid1 = fork();

if (pid1 < 0) {
fprintf(stderr, "Error creating child process P1\n");
return 1;
}
else if (pid1 == 0) {
// Code executed by P1 (first child)
printf("P1 (Child 1) - Process ID: %d\n", getpid());
}
else {
// Code executed by the parent process
// Create the second child process
pid2 = fork();

if (pid2 < 0) {
fprintf(stderr, "Error creating child process P2\n");
2
REPORT TITLE
return 1;
}
else if (pid2 == 0) {
// Code executed by P2 (second child)
printf("P2 (Child 2) - Process ID: %d\n", getpid());
}
else {
// Code executed by the parent process
printf("P (Parent) - Process ID: %d\n", getpid());
}
}

return 0;

3
REPORT TITLE
OUTPUT

4
REPORT TITLE
Question No # 2

Write a program using fork() system call to create a hierarchy of 3 process


such that P2 is the child of P1 and P1 is the child of P.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
pid_t pid1, pid2;

pid1 = fork();

if (pid1 < 0) {
fprintf(stderr, "Error creating child process P1\n");
return 1;
}
else if (pid1 == 0) {
// Code executed by P1 (first child)
printf("P1 (Child of P) - Process ID: %d\n", getpid());

// Create the second child process (P2)


pid2 = fork();

if (pid2 < 0) {
fprintf(stderr, "Error creating child process P2\n");
return 1;
}
else if (pid2 == 0) {
// Code executed by P2 (second child)
printf("P2 (Child of P1) - Process ID: %d\n", getpid());
}
5
REPORT TITLE
else {
// Code executed by P1
// P1 (Child of P) continues execution
// ... (optional additional code for P1)
}
}
else {
// Code executed by the parent process (P)
printf("P (Parent) - Process ID: %d\n", getpid());
}

return 0;
}

6
REPORT TITLE
Output

7
REPORT TITLE
8
REPORT TITLE
9
REPORT TITLE

You might also like