OneCompiler

os slip9

105

Q.1 Write a program to create a child process using fork().The parent should goto sleep state and child process should begin its execution. In the child process, use execl() to execute the
“ls” command.
ANSWER-1

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t child_pid = fork();
if (child_pid == 0) {
execl("/bin/ls", "ls", (char *)NULL);
perror("execl() failed");
} else if (child_pid > 0) {
sleep(5);
} else {
perror("Fork failed");
return 1;}
return 0;}

Q.2 Write the program to simulate Round Robin (RR) scheduling. The arrival time and first CPUburst for different n number of processes should be input to the algorithm. Also give the
time quantum as input. Assume the fixed IO waiting time (2 units). The next CPU-burst should be generated randomly. The output should give Gantt chart, turnaround time and waiting
time for each process. Also find the average waiting time and turnaround time.
ANSWER-2

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct { int a, b, r, t, w; } P;
int main() {
int n, q, s = 0, i = 0; srand(time(0));
printf("Enter n and quantum: "); scanf("%d%d", &n, &q);
P p[n]; for (int j = 0; j < n; j++) { p[j].a = j; p[j].b = rand() % 10 + 1; p[j].r = p[j].b; }
printf("Gantt Chart:\n");
while (1) {
int d = 1;
for (int j = 0; j < n; j++) {
if (p[j].r > 0) {
d = 0;
int u = p[j].r > q ? q : p[j].r;
p[j].r -= u; s += u;
printf("P%d ", j + 1);
p[j].a = s; p[j].r = 0;}}
if (d) break;}
printf("\nTurnaround\tWaiting\n");
for (int j = 0; j < n; j++) {
p[j].t = p[j].a - j;
p[j].w = p[j].t - p[j].b;
printf("P%d\t%d\t\t%d\n", j + 1, p[j].t, p[j].w);
i += p[j].t; q += p[j].w;}
printf("Avg TAT: %.2f\nAvg WT: %.2f\n", (float)i / n, (float)q / n);
return 0;