Professional Documents
Culture Documents
OS Assignment 1 (Daniyal Aqil 193 (E) )
OS Assignment 1 (Daniyal Aqil 193 (E) )
OS Assignment 1 (Daniyal Aqil 193 (E) )
Operating System
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
#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());
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