KEMBAR78
Fork Exec OS Lab Manual | PDF | Process (Computing) | Directory (Computing)
0% found this document useful (0 votes)
25 views56 pages

Fork Exec OS Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views56 pages

Fork Exec OS Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

lOMoARcPSD|40571466

OS lab manual 20ACS15 IT & CSO

Computer science and engineering (JNTUA COLLEGE OF ENGINEERING


ANANTAPURAM)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sana Saleem (sbunnypk47b@gmail.com)
lOMoARcPSD|40571466

SRI VENKATESWARA COLLEGE OF ENGINEERING

& TECHNOLOGY (Autonomous)


RVS NAGAR, TIRUPATI ROAD, CHITTOOR – 517127

DEPARTMENT OF IT & CSO

NAME OF THE LAB : OPERATING SYSTEM LAB

SUBJECT CODE : 20ACS15

YEAR / BRANCH : II B. Tech IT & CSO

NAME OF THE FACULTY : Mr. P. NANDA KUMAR

DESIGNATION : Assistant Professor

ACADEMIC YEAR : 2023-2024

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Syllabus

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

SRI VENKATESWARA COLLEGE OF ENGINEERING AND TECHNOLOGY

(Autonomous)

II B. Tech II Semester (Common to CSE, IT, CSE (DS) & CSE (AI &ML))
L T P C

- - 3 1.5
20ACS15 OPERATING SYSTEMS LAB

Course Outcome:
At the end of the course the student will be able to:
1. Execute the basic command in UNIX operating system and shell program.
2. Simulate the principles of CPU scheduling concepts.
3. Simulate the principles of synchronization and contiguous memory allocation technique.
4. Simulate the principle of page replacement algorithm

LIST OF EXPERIMENTS
1. Explain the following system calls in UNIX operating system (fork, exec, mkdir, cat,
open, date, history, clear, pwd, ls, cd)
2. Write a shell script program
(a) To perform arithmetic operations.
(b) To find the given number is odd or even
3. Implement the various process scheduling mechanisms such as FCFS, SJF, Priority, round
– robin.
4. Implement the solution for reader – writer’s problem.
5. Implement the solution for dining philosopher’s problem.
6. Implement banker’s algorithm.
7. Implement the first fit; best fit and worst fit file allocation strategy.
8. Write a C program to simulate page replacement algorithms a) FIFO b) LRU c) LFU
9. Write a C program to simulate disk scheduling algorithm a)FIFO b)SCAN c)CSCAN

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO1 3 2 1 3 3
CO2 3 3 2 3 1 3 3
CO3 3 2 1 3 3
CO4 3 2 3 3
3- High mapping 2-Medium Mapping 1- Low Mapping

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Index of
Experiments

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

S.N. Page Name of Experiments Signature Remarks


No

1. 01-06 Explain the following system calls in UNIX operating


system (fork, exec, mkdir, cat, open, date, history, clear,
pwd, ls, cd)

2. 07-08 Write a shell script program


(a) To perform arithmetic operations.
(b) To find the given number is odd or even.

3. 09-16 Implement the various process scheduling mechanisms


such as FCFS, SJF, Priority, round – robin.

4. 17-19 Implement the solution for reader – writer’s problem.

5. Implement the solution for dining philosopher’s


20-23 problem.

6. 24-25 Implement banker’s algorithm.

7. Implement the first fit; best fit and worst fit file
allocation strategy.
26-29

8. 30-25 Write a C program to simulate page replacement


algorithms
a) FIFO b) LRU c) LFU

9. 36-41 Write a C program to simulate disk scheduling


algorithm
a)FIFO b)SCAN c)CSCAN

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Experiment No. 1
Explain the following system calls in UNIX operating system (fork, exec, mkdir, cat, open, date, history,
clear, pwd, ls, cd)

Aim:-
To execute the following system calls in UNIX operating system.

Unix System Calls


System calls in Unix are used for file system control, process control, interprocess communication
etc. Access to the Unix kernel is only available through these system calls. Generally, system calls
are similar to function calls, the only difference is that they remove the control from the user
process.
• There are around 80 system calls in Unix interface currently.
• The interface between a process and an operating system is provided by system calls. In
general, system calls are available as assembly language instructions

COMMAND
1.) fork()

Fork system call is used for creating a new process, which is called child process, which runs concurrently
with the process that makes the fork() call (parent process). After a new child process is created, both
processes will execute the next instruction following the fork() system call. A child process uses the same
pc(program counter), same CPU registers, same open files which use in the parent process.

• It takes no parameters and returns an integer value.


• Negative Value:- creation of a child process was unsuccessful.
• Zero :- Returned to the newly created child process.
• Positive value:- Returned to parent or caller. The value contains process ID of newly created child
process.
Note:-
1. Please note that the above program don’t compile in windows environment.
2. Use online compiler:- https://www.programiz.com/c-programming/online-compiler/

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

PROGRAM
#include <stdio.h>
#include<stdio.h>
#include <sys/types.h>
#include<sys/types.h>
int main()
#include<unistd.h>
{
void main()
fork();
{
fork();
// make two process which run same
fork();
// program after this instruction
printf("hello\n");
fork();
return 0;
}
printf("Hello world!\n");
Output
hello
}
hello
Output:-
hello
hello
Hello world!
hello
Hello world!
hello
hello
hello

2. exec()

exec command in Linux is used to execute a command from the bash itself. This command does not create
a new process it just replaces the bash with the command to be executed. If the exec command is
successful, it does not return to the calling process.

Syntax:-
exec [-cl] [-a name] [command [arguments]] [redirection ...]
Options:
c: It is used to execute the command with empty environment.
a name: Used to pass a name as the zeroth argument of the command.
l: Used to pass dash as the zeroth argument of the command.
Note: exec command does not create a new process. When we run the exec command from the terminal,
the ongoing terminal process is replaced by the command that is provided as the argument for the exec
command.

Command
echo 'this is the input text.'>in.txt
exec wc -w < in.txt
Output:-
5
File cretead
In.txt
this is the input text

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

3. Mkdir()

To create or make a new directory in a current directory.


Syntax:- $mkdir<directory name>

We have used ‘$ cd’ (below) to get into the newly created directory and again on giving ‘$ pwd’
command,we are displayed with the new ‘newfolder’ directory.

Command

$ mkdir newfolder
$ cd newfolder
$ pwd
Output: /home/kali/newfolder

4. cat()
Cat is shoít foí concatenate. ľhis command displays the contents of one oí moíe files without having to o pen
the file foí editing.
Syntax
cat [options] filename(s)

• [options] –additional instíuctions to the cat command.

Foí example, to display the contents of a file with each line numbeíed, use the –n option:

cat –n filename

filename(s) – Specify the name of the file (oí files) that you want to display

Examples:-
1. Create a New file
cat >test1.txt

2. Display contents of a file

cat test1.txt

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

5. open -

Used to Open the file for reading, writing or both.

How it works in OS

• Find the existing file on disk


• Create file table entry
• Set first unused file descriptor to point to file table entry

Syntax

$ open foldername

Command:-

$open newfolder

6. Date Command :
This command is used to display the current data and time.

Command

$date

$date +%ch

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Options : -

a = Abbrevated weekday. L = Day of the year.


A = Full weekday. m = Month of the year.
b = Abbrevated month. M = Minute.
B = Full month. P = Display AM or PM
c = Current day and time. S = Seconds
C = Display the century as a decimal number. T = HH:MM:SS format
d = Day of the month. u = Week of the year.
D = Day in „mm/dd/yy‟ format y = Display the year in 2 digit.
h = Abbrevated month day. Y = Display the full year.
H = Display the hour. Z = Time zone .

To change the format :

Syntax : $date ‘+%H-%M-%S’

7. History
One of the extensively used command in UNIX world is the history command. The bash shell stores a
history of commands entered, which can be used to repeat commands by using the history command. By
default, it’ll show the previous 1000 commands that were used.

COMMAND

$ history

Output

1 shutdown

2 shutdown -c

3 shutdown -h now

4 help

5 sudo

6 sudo apt

7 read a b

........

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

8. clear

The ‘$ clear’ command is used to clean up the terminal so that you can type with more accuracy

COMMAND

$ clear

Output

9. pwd
The ‘$pwd’ command stands for ‘print working directory’ and as the name says,it displays the directory in
which we are currently (directory is same as folder for Windows OS users).
In the output we are sike directory(folder for Windows OS that are moving to Linux),which is present
inside the home directory .

Command

$ pwd

Output: /home/kali

10. ls
The ‘ls’ command simply displays the contents of a directory.

$ ls

Output 1:

Desktop Documents Downloads in.txt Music newfolder Pictures Public sikendar spaceAPI Templates
test1.txt Videos

11. cd
The ‘$ cd’ command stands for ‘change directory’ and it changes your current directory to the ‘newfolder’
directory. You can understand this a double-clicking a folder and then you do some stuff in that folder.

$ cd newfolder

#(assuming that there is a directory named 'newfolder' on your system)

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Exp.No. 2a

Write a shell script program

a) To perform arithmetic operations.


b) To find the given number is odd or even

Aim:

To write a shell program to perform the arithmetic operations using case.

Algorithm
Step 1 : Read the input variables and assign the value
Step 2 : Perform the various arithmetic operations
Step 3 : Print the result after the arithmetic
operations.
Step 4 : Stop

Command
echo Enter the first number
read a
echo Enter the second number
read b
echo `expr $a + $b`
echo `expr $a - $b`
echo `expr $a \* $b`
echo `expr $a / $b`
echo `expr $a % $b`
Output
Enter the first number
10
Enter the second number
2
12
8
20
5
0

Result:-
Thus the shell program to perform arithmetic operation is executed and output is verified successfully.

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

2. b) To check the given number is even or odd


ALGORITHM
Step 1 : Start the progam.
STEP 2: Read the value of n.
STEP 3: Calculate “r=expr $n%2”.
STEP 4: If the value of r equals 0 then print the number is even
STEP 5: If the value of r not equal to 0 then print the number is odd.
STEP 6 : Stop

Command

echo "Enter the Number"


read n
r=`expr $n % 2`
if [ $r -eq 0 ]
then echo "$n is Even number"
else
echo "$n is Odd number"
fi

SAMPLE OUTPUT 1

Enter the Number


43
43 is Odd number

SAMPLE OUTPUT 2
Enter the Number
88
88 is Even number

Result:-
Thus the shell program to perform find the given number is odd or even is executed and output is
verified successfully.

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

ExNo:3 a FIRST COME FIRST SERVE

AIM:
To write a C program to implement the CPU scheduling algorithm for FIRST COME FIRST SERVE.

PROBLEM DESCRIPTION:
Cpu scheduler will decide which process should be given the CPU for its execution. . For this it use
different algorithm to choose among the process. one among that algorithm is sjf algorithm.
In this algorithm the process which arrive first is given the cpu after finishing its request only it will allow
cpu to execute other process.

ALGORITHM:
Step1: Start
Step2: Declare the array size
Step3: Read the number of processes to be inserted
Step4: Read the Burst time of processes.
Step5: Calculate the waiting time of each process w[i+1]=bt[i]+wt[i]
Step6: Calculate the turnaround time of each process tt[i+1]=tt[i]+bt[i+1]
Step7 : Calculate
• Average waiting time = Total waiting time/No of process
• Average turnaround time = Total turn around time/no of process
Step 8 : Stop

PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
int i,bt[20],wt[20],tat[20],n;
float wtavg,tatavg;
printf("\n Enter the number of process --");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst time for process %d --",i);
scanf("%d",&bt[i]);
}
wt[0]=wtavg=0;
tat[0]=tatavg=bt[0];
for(i=1;i<n;i++)
{

wt[i]=wt[i-1]+bt[i-1];
tat[i]=tat[i-1]+bt[i];
wtavg=wtavg+wt[i];
tatavg=tatavg+tat[i];
}

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

printf("\t PROCESS \t BURST TIME \t WAITING TIME \t TURNAROUND TIME \n");


for(i=0;i<n;i++)
printf("\n \t P%d \t\t %d \t\t %d \t\t %d",i,bt[i],wt[i],tat[i]);
printf("\nAverage waiting time -- %f",wtavg/n);
printf("\nAverage Turnaround Time -- %f",tatavg/n);
getch();
}

Output:-

RESULT:
Thus the C program to implement CPU scheduling algorithm for first come first serve was executed
successfully.

10

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

SHORTEST JOB FIRST


AIM:
To write a C program to implement the CPU scheduling algorithm for Shortest job first.

PROBLEM DESCRIPTION:
In this algorithm the process which has less service time given the cpu after finishing its request only it
will allow cpu to execute next other process.

ALGORITHM:
1. Start
2. Declare the array size
3. Read the number of processes to be inserted
4. Read the Burst times of processes
5. sort the Burst times in ascending order and process with shortest burst time is first executed.
6. calculate the waiting time of each process wt[i+1]=bt[i]+wt[i]
7. calculate the turnaround time of each process tt[i+1]=tt[i]+bt[i+1]
8. Calculate the average waiting time and average turnaround time.
9. Display the values
10. Stop

Program
#include<stdio.h>
#include<conio.h>
main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
//clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}

11

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}

OUTPUT

Result
Thus the C program to implement the CPU scheduling algorithm for shortest job first was executed
successfully.

12

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

PRIORITY SCHEDULING

AIM:
To write a C program to implement CPU scheduling algorithm for priority scheduling.
PROBLEM DESCRIPTION:
In this algorithm the process which arrive first is given the cpu after finishing its request only it will
allow cpu to execute other process.

ALGORITHM:
1. Start
2. Declare the array size
3. Read the number of processes to be inserted
4. Read the Priorities of processes
5. sort the priorities and Burst times in ascending order
calculate the waiting time of each process wt[i+1]=bt[i]+wt[i]
6. calculate the turnaround time of each process tt[i+1]=tt[i]+bt[i+1]
Calculate the average waiting time and average turnaround time.
7. Display the values
8. Stop

PROGRAM
#include<stdio.h>
main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
//clrscr();
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i);
scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;

13

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
getch();
}

OUTPUT

RESULT:
Thus C program to implement CPU scheduling algorithm for round robin scheduling was executed
successfully.

14

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

ROUND ROBIN
AIM :
To write a C program to simulate the CPU scheduling algorithm for round robin.

PROBLEM DESCRIPTION:
In this algorithm we are assigning some time slice. The process is allocated according to the time slice ,if
the process service time is less than the time slice then process itself will release the CPU voluntarily.
The scheduler will then proceed to the next process in the ready queue. If the CPU burst of the currently
running process is longer than time quantum ,the timer will go off and will cause an interrupt to the
operating system .A context switch will be executed and the process will be put at the tail of the ready
queue.

ALGORITHM:
1. Start
2. Declare the array size
3. Read the number of processes to be inserted
4. Read the burst times of the processes
5. Read the Time Quantum
6. if the burst time of a process is greater than time Quantum then subtract time quantum form the
burst time Else Assign the burst time to time quantum.
7.calculate the average waiting time and turn around time of the processes.
8. Display the values
9. Stop
PROGRAM
#include<stdio.h>
main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
//clrscr();
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)

15

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
getch();
}

OUTPUT

RESULT:
Thus the C program to simulate CPU scheduling algorithm for round robin was executed successfully

16

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Ex. No 4

4) Implement the solution for reader writer’s problem

Aim

To implement the solution for reader writer’s problem.

17

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

PROGRAM

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

/*
This program provides a possible solution for first readers writers problem using mutex and semaphore.
I have used 10 readers and 5 producers to demonstrate the solution. You can always play with these
values.
*/

sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;

void *writer(void *wno)


{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);
sem_post(&wrt);

}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);

// Reader acquire the lock before modifying numreader


pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
sem_post(&wrt); // If this is the last reader, it will wake up the writer.
}
pthread_mutex_unlock(&mutex);
}

int main()
{

18

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);

int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering the producer and consumer

for(int i = 0; i < 10; i++) {


pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for(int i = 0; i < 5; i++) {
pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i]);
}

for(int i = 0; i < 10; i++) {


pthread_join(read[i], NULL);
}
for(int i = 0; i < 5; i++) {
pthread_join(write[i], NULL);
}

pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}

OUTPUT

19

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Ex. No. 5

5) Implement the solution for dining philosopher’s problem.

Aim

To implement the solution for dining philosopher’s problem.

Algorithm

Step 1: Start

Step 2 : Import the libraries for threads and semaphore for synchronization.

Step 3: create an array of 5 p_threads representing the philosophers.

Step 4 : Create an array of 5 mutexes representing the chopsticks.

Step 5 : initialise the counter i and status message variable as int and a pointer msg, and intialise the
semaphore array.

Step 6 : create the philosopher threads using pthread_create and pass a pointer to the dine function as
the subroutine and a pointer to the counter variable i.

Step 7: All the philosophers start by thinking. We pass chopstick(n) (left) to pthread_mutex_lock to wait
and acquire lock on it.

Step 8: Then the thread waits on the right((n+1) % NUM_CHOPSTICKS) chopstick to acquire a lock on it
(pick it up).

Step 9: When the philosopher successfully acquires lock on both the chopsticks, the philosopher starts
dining (sleep(3)).

Step 10: Once the philosopher finishes eating, we call pthread_mutex_unlock on the left chopstick
(signal) thereby freeing the lock. Then proceed to do the same on the right chopstick.

Step 11: We loop through all philosopher threads and call pthread_join to wait for the threads to finish
executing before exiting the main thread.

20

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Step 12: We loop thorough the chopstick array and call pthread_mutex_destroy to destroy the
semaphore array.

Step 13 : Terminate the program.

Program
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5

void dine(int n);


pthread_t philosopher[NUM_PHILOSOPHERS];
pthread_mutex_t chopstick[NUM_CHOPSTICKS];

int main()
{
int i, status_message;
void *msg;

// Initialise the semaphore array


for (i = 1; i <= NUM_CHOPSTICKS; i++)
{
status_message = pthread_mutex_init(&chopstick[i], NULL);
// Check if the mutex is initialised successfully
if (status_message == -1)
{
printf("\n Mutex initialization failed");
exit(1);
}
}

// Run the philosopher Threads using *dine() function


for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_create(&philosopher[i], NULL, (void *)dine, (int *)i);
if (status_message != 0)
{
printf("\n Thread creation error \n");
exit(1);
}
}

// Wait for all philosophers threads to complete executing (finish dining) before closing the program
for (i = 1; i <= NUM_PHILOSOPHERS; i++)

21

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

{
status_message = pthread_join(philosopher[i], &msg);
if (status_message != 0)
{
printf("\n Thread join failed \n");
exit(1);
}
}

// Destroy the chopstick Mutex array


for (i = 1; i <= NUM_CHOPSTICKS; i++)
{
status_message = pthread_mutex_destroy(&chopstick[i]);
if (status_message != 0)
{
printf("\n Mutex Destroyed \n");
exit(1);
}
}
return 0;
}
void dine(int n)
{
printf("\nPhilosopher % d is thinking ", n);

// Philosopher picks up the left chopstick (wait)


pthread_mutex_lock(&chopstick[n]);

// Philosopher picks up the right chopstick (wait)


pthread_mutex_lock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);

// After picking up both the chopstick philosopher starts eating


printf("\nPhilosopher % d is eating ", n);
sleep(3);

// Philosopher places down the left chopstick (signal)


pthread_mutex_unlock(&chopstick[n]);

// Philosopher places down the right chopstick (signal)


pthread_mutex_unlock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);

printf("\nPhilosopher % d Finished eating ", n);


}

22

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

OUTPUT

Philosopher 2 is thinking
Philosopher 2 is eating
Philosopher 3 is thinking
Philosopher 5 is thinking
Philosopher 5 is eating
Philosopher 1 is thinking
Philosopher 4 is thinking
Philosopher 4 is eating
Philosopher 2 Finished eating
Philosopher 5 Finished eating
Philosopher 1 is eating
Philosopher 4 Finished eating
Philosopher 3 is eating
Philosopher 1 Finished eating
Philosopher 3 Finished eating

23

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Ex. No. 6

6) Implement banker’s algorithm

Aim

To implement Banker’s algorithm

Banker ‘s Algorithm:
When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of
resources in the system. When the user requests a set of resources, the system must
determine whether the allocation of each resource will leave the system in safe state. If
it will the resources are allocation; otherwise, the process must wait until some other
process release the resources.

ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state
8. Stop the process.

SOURCE CODE

#include<stdio.h>
#include<conio.h>
void main()
{
char job[10][10];
int time[10],avail,tem[10],temp[10]; int safe[10];
int ind=1,i,j,q,n,t;
//clrscr();
printf("Enter no of jobs: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name and time: ");
scanf("%s%d",&job[i],&time[i]);
}
printf("Enter the available resources:");
scanf("%d",&avail);
for(i=0;i<n;i++)
{
temp[i]=time[i];
tem[i]=i;

24

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(temp[i]>temp[j])
{
t=temp[i];
temp[i]=temp[j];
temp[j]=t; t=tem[i];
tem[i]=tem[j];
tem[j]=t;
}
}
for(i=0;i<n;i++)
{
q=tem[i];
if(time[q]<=avail)
{
safe[ind]=tem[i];
avail=avail-tem[q];
printf("%s",job[safe[ind]]);
ind++;
}
else
{
printf("No safe sequence\n");
}
}
printf("Safe sequence is:");
for(i=1;i<ind; i++)
printf("%s %d\n",job[safe[i]],time[safe[i]]);
getch();
}

Output

Enter no of jobs:4
Enter name and time: A 1
Enter name and time: B 4
Enter name and time: C 2
Enter name and time: D 3
Enter the available resources: 20
Safe sequence is: A 1, C 2, D 3, B 4.

25

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Ex. No. 7

7) Implement the first fit, best fit and worst fit file allocation strategy

AIM:

To write a C program to implement Memory Management concept using the

technique best fit, worst fit and first fit algorithms.

ALGORITHM:
1. Get the number of process.
2. Get the number of blocks and size of process.
3. Get the choices from the user and call the corresponding switch cases.
4. First fit -allocate the process to the available free block match with the size of
the process
5. Worst fit –allocate the process to the largest block size available in the list
6. Best fit-allocate the process to the optimum size block available in the list
7. Display the result with allocations

PROGRAM

#include<stdio.h>
main()
{
int p[10],np,b[10],nb,ch,c[10],d[10],alloc[10],flag[10],i,j;
printf("\nEnter the no of process:");
scanf("%d",&np);
printf("\nEnter the no of blocks:");
scanf("%d",&nb);
printf("\nEnter the size of each process:");
for(i=0;i<np;i++)
{
printf("\nProcess %d:",i);
scanf("%d",&p[i]);
}
printf("\nEnter the block sizes:");
for(j=0;j<nb;j++)
{
printf("\nBlock %d:",j);
scanf("%d",&b[j]);c[j]=b[j];d[j]=b[j];
}
if(np<=nb)
{
printf("\n1.First fit 2.Best fit 3.Worst fit");
do
{
printf("\nEnter your choice:");
scanf("%d",&ch);

26

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

switch(ch)
{
case 1: printf("\nFirst Fit\n");
for(i=0;i<np;i++)
{
for(j=0;j<nb;j++)
{
if(p[i]<=b[j])
{
alloc[j]=p[i];printf("\n\nAlloc[%d]",alloc[j]);
printf("\n\nProcess %d of size %d isallocated in block:%d of size:%d",i,p[i],j,b[j]);
flag[i]=0,b[j]=0;break;
}
else
flag[i]=1;
}
}
for(i=0;i<np;i++)
{
if(flag[i]!=0)
printf("\n\nProcess %d of size %d is notallocated",i,p[i]);
}
break;
case 2: printf("\nBest Fit\n");
for(i=0;i<nb;i++)
{
for(j=i+1;j<nb;j++)
{
if(c[i]>c[j])
{
int temp=c[i];
c[i]=c[j];
c[j]=temp;
}}}
printf("\nAfter sorting block sizes:");
for(i=0;i<nb;i++)
printf("\nBlock %d:%d",i,c[i]);
for(i=0;i<np;i++)
{
for(j=0;j<nb;j++)
{
if(p[i]<=c[j])
{
alloc[j]=p[i];
printf("\n\nAlloc[%d]",alloc[j]);
printf("\n\nProcess %d of size %d is allocated in block %d of size%d",i,p[i],j,c[j]);
flag[i]=0,c[j]=0;break;
}

27

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

else
flag[i]=1;
}
}
for(i=0;i<np;i++)
{
if(flag[i]!=0)
printf("\n\nProcess %d of size %d is not allocated",i,p[i]);
}
break;
case 3: printf("\nWorst Fit\n");
for(i=0;i<nb;i++)
{
for(j=i+1;j<nb;j++)
{
if(d[i]<d[j])
{
int temp=d[i];
d[i]=d[j];
d[j]=temp;
}} }
printf("\nAfter sorting block sizes:");
for(i=0;i<nb;i++)
printf("\nBlock %d:%d",i,d[i]);
for(i=0;i<np;i++)
{
for(j=0;j<nb;j++)
{
if(p[i]<=d[j])
{
alloc[j]=p[i];
printf("\n\nAlloc[%d]",alloc[j]);
printf("\n\nProcess %d of size %d is allocated in block %d of size%d",i,p[i],j,d[j]);
flag[i]=0,d[j]=0;break;
}
else
flag[i]=1;
}}
for(i=0;i<np;i++)
{
if(flag[i]!=0)
printf("\n\nProcess %d of size%d is not allocated",i,p[i]);
}
break;
default: printf("Invalid Choice…!");break;
}
}while(ch<=3);
}

28

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

}
OUTPUT
Enter the no of process:3
Enter the no of blocks:3
Enter the size of each process:
Process 0:100
Process 1:150
Process 2:200
Enter the block sizes:
Block 0:300
Block 1:350
Block 2:200
1.First fit 2.Best fit 3.Worst fit
Enter your choice:1
Alloc[100]
Process 0 of size 100 is allocated in block 0 of size 300
Alloc[150]
Process 1 of size 150 is allocated in block 1 of size 350
Alloc[200]
Process 2 of size 200 is allocated in block 2 of size 200
Enter your choice:2
Best Fit
After sorting block sizes are:
Block 0:200
Block 1:300
Block 2:350
Alloc[100]
Process 0 of size 100 is allocated in block:0 of size:200
Alloc[150]
Process 1 of size 150 is allocated in block:1 of size:300
Alloc[200]
Process 2 of size 200 is allocated in block:2 of size:350
enter your choice:3
Worst Fit
After sorting block sizes are:
Block 0:350
Block 1:300
Block 2:200
Alloc[100]
Process 0 of size 100 is allocated in block 0 of size 350
Alloc[150]
Process 1 of size 150 is allocated in block 1 of size 300
Alloc[200]
Process 2 of size 200 is allocated in block 2 of size 200
Enter your choice:6
Invalid Choice…!

29

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

8) Write a C program to simulate page replacement algorithms

a) FIFO b) LRU c) LFU

AIM:
To write a C program to implement FIFO page replacement algorithm.
DESCRIPTION:
The FIFO Page Replacement algorithm associates with each page the time when that
page was brought into memory. When a page must be replaced, the oldest page is
chosen. There is not strictly necessary to record the time when a page is brought in.
By creating a FIFO queue to hold all pages in memory and by replacing the page at
the head of the queue. When a page is brought into memory, insert it at the tail of
the queue.
ALGORITHM:
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Format queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the process
PROGRAM:

#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
//clrscr();
printf("\n Enter the length of reference string -- ");
scanf("%d",&n);
printf("\n Enter the reference string -- ");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\n Enter no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
m[i]=-1;
printf("\n The Page Replacement Process is -- \n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
if(m[k]==rs[i])

30

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

break;
}
if(k==f)
{
m[count++]=rs[i];
pf++;
}
for(j=0;j<f;j++)
printf("\t%d",m[j]);
if(k==f)
printf("\tPF No. %d",pf);
printf("\n");
if(count==f)
count=0;
}
printf("\n The number of Page Faults using FIFO are %d",pf);
getch();
}
OUTPUT

Enter the length of reference string – 20


Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3
The Page Replacement Process is –
7 -1 -1 PF No. 1
7 0 -1 PF No. 2
7 0 1 PF No. 3
2 0 1 PF No. 4
201
2 3 1 PF No. 5
2 3 0 PF No. 6
4 3 0 PF No. 7
4 2 0 PF No. 8
4 2 3 PF No. 9
0 2 3 PF No. 10
023
023
0 1 3 PF No. 11
0 1 2 PF No. 12
012
012
7 1 2 PF No. 13
7 0 2 PF No. 14
7 0 1 PF No. 15
The number of Page Faults using FIFO are 15
RESULT:
Thus a C program to implement FIFO page replacement is executed successfully.

31

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

EX.NO:8. B) IMPLEMENTATION OF LRU PAGE REPLACEMENT

AIM:
To write C program a program to implement LRU page replacement algorithm.
DESCRIPTION:
The Least Recently Used replacement policy chooses to replace the page which has
not been referenced for the longest time. This policy assumes the recent past will
approximate the immediate future. The operating system keeps track of when each
page was referenced by recording the time of reference or by maintaining a stack of
references.
ALGORITHM:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process
PROGRAM:

#include<stdio.h>
#include<conio.h>
main()
{
int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1;
//clrscr();
printf("Enter the length of reference string -- ");
scanf("%d",&n);
printf("Enter the reference string -- ");
for(i=0;i<n;i++)
{
scanf("%d",&rs[i]); flag[i]=0;
}
printf("Enter the number of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
{
count[i]=0;
m[i]=-1;
}
printf("\nThe Page Replacement process is -- \n");
for(i=0;i<n;i++){
for(j=0;j<f;j++){
if(m[j]==rs[i])
{
flag[i]=1;

32

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

count[j]=next;
next++;
}
}
if(flag[i]==0)
{
if(i<f)
{
m[i]=rs[i];
count[i]=next;
next++;
}
else
{
min=0;
for(j=1;j<f;j++)
if(count[min] > count[j])
min=j;
m[min]=rs[i];
count[min]=next;
next++;
}
pf++;
}
for(j=0;j<f;j++)
printf("%d\t", m[j]);
if(flag[i]==0)
printf("PF No. -- %d" , pf);
printf("\n");
}
printf("\nThe number of page faults using LRU are %d",pf);
getch();
}
OUTPUT

Enter the length of reference string -- 20


Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter the number of frames -- 3
The Page Replacement process is --
7 -1 -1 PF No. -- 1
7 0 -1 PF No. -- 2
7 0 1 PF No. -- 3
2 0 1 PF No. -- 4
201
2 0 3 PF No. -- 5
203
4 0 3 PF No. -- 6
4 0 2 PF No. -- 7

33

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

4 3 2 PF No. -- 8
0 3 2 PF No. -- 9
032
032
1 3 2 PF No. -- 10
132
1 0 2 PF No. -- 11
102
1 0 7 PF No. -- 12
107
107
The number of page faults using LRU are 12
RESULT:
Thus a UNIX C program to implement LRU page replacement is executed
successfully.

EX.NO:8C IMPLEMENTATION OF LFU PAGE REPLACEMENT

AIM:
To write a program in C to implement LFU page replacement algorithm.
ALGORITHM
Step1: Start the program
Step2: Declare the required variables and initialize it.
Step3; Get the frame size and reference string from the user
Step4: Keep track of entered data elements
Step5: Accommodate a new element look for the element that is not to be used in
frequently replace.
Step6: Count the number of page fault and display the value
Step7: Terminate the program
PROGRAM
#include<stdio.h>
#include<conio.h>
main()
{
int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0;
//clrscr();
printf("\nEnter number of page references -- ");
scanf("%d",&m);
printf("\nEnter the reference string -- ");
for(i=0;i<m;i++)
scanf("%d",&rs[i]);
printf("\nEnter the available no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
{
cntr[i]=0;

34

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

a[i]=-1;
}
printf("\nThe Page Replacement Process is – \n");
for(i=0;i<m;i++)
{
for(j=0;j<f;j++)
if(rs[i]==a[j])
{
cntr[j]++;
break;
}
if(j==f){
min = 0;
for(k=1;k<f;k++)
if(cntr[k]<cntr[min])
min=k;
a[min]=rs[i];
cntr[min]=1;
pf++;
}
printf("\n");
for(j=0;j<f;j++)
printf("\t%d",a[j]);
if(j==f)
printf("\tPF No. %d",pf);
}
printf("\n\n Total number of page faults -- %d",pf);
getch();
}
OUTPUT
Enter number of page references -- 10
Enter the reference string -- 1 2 3 4 5 2 5 2 5 1 4 3
Enter the available no. of frames 3
The Page Replacement Process is –
1 -1 -1 PF No. 1
1 2 -1 PF No. 2
1 2 3 PF No. 3
4 2 3 PF No. 4
5 2 3 PF No. 5
523
523
5 2 1 PF No. 6
5 2 4 PF No. 7
5 2 3 PF No. 8
Total number of page faults -- 8
RESULT:
Thus the C programs to implement LFU page replacement algorithm was
executed successfully.

35

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

9) Write a C program to simulate disk scheduling algorithm


a) FIFO b) SCAN c) CSCAN
FIFO
Aim
To write a c program to simulate FIFO disk scheduling algorithm

Algorithm
1. Let Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. ‘head’ is the position of disk head.
2. Let us one by one take the tracks in default order and calculate the absolute distance of
the track from the head.
3. Increment the total seek count with this distance.
4. Currently serviced track position now becomes the new head position.
5. Go to step 2 until all tracks in request array have not been serviced.

Source Code
#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the initial head position\n");
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}

36

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

OUTPUT

SCAN
Aim
To write a C program to simulate SCAN disk scheduling algorithm.

Algorithm
1. Let Request array represents an array storing indexes of tracks that have been requested
in ascending order of their time of arrival. ‘head’ is the position of disk head.
2. Let direction represents whether the head is moving towards left or right.
3. In the direction in which head is moving service all tracks one by one.
4. Calculate the absolute distance of the track from the head.
5. Increment the total seek count with this distance.
6. Currently serviced track position now becomes the new head position.

37

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

7. Go to step 3 until we reach at one of the ends of the disk.


8. If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in
request array have not been serviced.
Program
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,sum=0,n;
int d[20];
int disk; //loc of head
int temp,max;
int dloc; //loc of disk in array
//clrscr();
printf("enter number of location\t");
scanf("%d",&n);
printf("enter position of head\t");
scanf("%d",&disk);
printf("enter elements of disk queue\n");
for(i=0;i<n;i++)
{
scanf("%d",&d[i]);
}
d[n]=disk;
n=n+1;
for(i=0;i<n;i++) // sorting disk locations
{
for(j=i;j<n;j++)
{
if(d[i]>d[j])
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}
}
max=d[n];
for(i=0;i<n;i++) // to find loc of disc in array
{
if(disk==d[i]) { dloc=i; break; }
}
for(i=dloc;i>=0;i--)
{
printf("%d -->",d[i]);
}
printf("0 -->");
for(i=dloc+1;i<n;i++)

38

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

{
printf("%d-->",d[i]);
}
sum=disk+max;
printf("\nmovement of total cylinders %d",sum);
getch();
return 0;
}

Output
Enter no of location 8
Enter position of head 53
Enter elements of disk queue
98
183
37
122
14
124
65
67
53->37->14->0->65->67->98->122->124->183->
Movement of total cylinders 236.

CSCAN
Aim
To write a C program to simulate disk scheduling algorithm using CSCAN

Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. ‘head’ is the position of disk head.
2. The head services only in the right direction from 0 to the size of the disk.
3. While moving in the left direction do not service any of the tracks.
4. When we reach the beginning(left end) reverse the direction.
5. While moving in the right direction it services all tracks one by one.
6. While moving in the right direction calculate the absolute distance of the track from the head.
7. Increment the total seek count with this distance.
8. Currently serviced track position now becomes the new head position.
9. Go to step 6 until we reach the right end of the disk.
10. If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in the
request array have not been serviced.

Source Code
#include<stdio.h>
int main()
{

39

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
{
scanf("%d",&temp);
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]>queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}

40

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
queue[i]=max;
queue[i+1]=0;
for(i=temp1+3,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n+1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}

Output

41

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

SRI VENKATESWARA COLLEGE OF ENGINEERING AND TECHNOLOGY


(AUTONOMOUS)
20ACS15 OPERATING SYSTEMS LAB VIVA Q & A
1) What is an operating system?
The operating system is a software program that facilitates computer hardware to communicate
and operate with the computer software. It is the most important part of a computer system
without it computer is just like a box.

2) What is the main purpose of an operating system?


There are two main purposes of an operating system:
• It is designed to make sure that a computer system performs well by managing its
computational activities.
• It provides an environment for the development and execution of programs.

3) What are the different operating systems?


• Batched operating systems
• Distributed operating systems
• Timesharing operating systems
• Multi-programmed operating systems
• Real-time operating systems

4) What is a socket?
A socket is used to make connection between two applications. Endpoints of the connection
are called socket.

5) What is a real-time system?


Real-time system is used in the case when rigid-time requirements have been placed on the
operation of a processor. It contains a well-defined and fixed time constraints.

6) What is kernel?
Kernel is the core and most important part of a computer operating system which provides
basic services for all parts of the OS.

7) What is monolithic kernel?


A monolithic kernel is a kernel which includes all operating system code is in single executable
image.

8) What do you mean by a process?


An executing program is known as process. There are two types of processes:
Operating System Processes and User Processes

42

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

9) What are the different states of a process?


A list of different states of process:
New Process, Running Process, Waiting Process, Ready Process and Terminated Process.

10) What is the difference between micro kernel and macro kernel?
Micro kernel: micro kernel is the kernel which runs minimal performance affecting services
for operating system. In micro kernel operating system all other operations are performed by
processor.
Macro Kernel: Macro Kernel is a combination of micro and monolithic kernel.

11) What is the concept of reentrancy?


It is a very useful memory saving technique that is used for multi-programmed time sharing
systems. It provides functionality that multiple users can share a single copy of program during
the same period.
It has two key aspects:
The program code cannot modify itself.
The local data for each user process must be stored separately.

12) What is the difference between process and program?


A program while running or executing is known as a process.

13) What is the use of paging in operating system?


Paging is used to solve the external fragmentation problem in operating system. This technique
ensures that the data you need is available as quickly as possible.

14) What is the concept of demand paging?


Demand paging specifies that if an area of memory is not currently being used, it is swapped
to disk to make room for an application's need.

15) What is the advantage of a multiprocessor system?


As many as processors are increased, you will get the considerable increment in throughput. It
is cost effective also because they can share resources. So, the overall reliability increases.

16) What is virtual memory?


Virtual memory is a very useful memory management technique which enables processes to
execute outside of memory. This technique is especially used when an executing program
cannot fit in the physical memory.

17) What is thrashing?


Thrashing is a phenomenon in virtual memory scheme when the processor spends most of its
time in swapping pages, rather than executing instructions.

18) What are the four necessary and sufficient conditions behind the deadlock?
These are the 4 conditions:

43

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

1) Mutual Exclusion Condition: It specifies that the resources involved are non-sharable.
2) Hold and Wait Condition: It specifies that there must be a process that is holding a resource
already allocated to it while waiting for additional resource that are currently being held by
other processes.
3) No-Preemptive Condition: Resources cannot be taken away while they are being used by
processes.
4) Circular Wait Condition: It is an explanation of the second condition. It specifies that the
processes in the system form a circular list or a chain where each process in the chain is waiting
for a resource held by next process in the chain.

19) What is a thread?


A thread is a basic unit of CPU utilization. It consists of a thread ID, program counter, register
set and a stack.

20) What is FCFS?


FCFS stands for First Come, First Served. It is a type of scheduling algorithm. In this scheme,
if a process requests the CPU first, it is allocated to the CPU first. Its implementation is
managed by a FIFO queue.

21) What is SMP?


SMP stands for Symmetric MultiProcessing. It is the most common type of multiple processor
system. In SMP, each processor runs an identical copy of the operating system, and these copies
communicate with one another when required.

22) What is RAID? What are the different RAID levels?


RAID stands for Redundant Array of Independent Disks. It is used to store the same data
redundantly to improve the overall performance.
Following are the different RAID levels:
RAID 0 - Stripped Disk Array without fault tolerance
RAID 1 - Mirroring and duplexing
RAID 2 - Memory-style error-correcting codes
RAID 3 - Bit-interleaved Parity
RAID 4 - Block-interleaved Parity
RAID 5 - Block-interleaved distributed Parity
RAID 6 - P+Q Redundancy

23) What is deadlock? Explain.


Deadlock is a specific situation or condition where two processes are waiting for each other to
complete so that they can start. But this situation causes hang for both of them.

24) Which are the necessary conditions to achieve a deadlock?


There are 4 necessary conditions to achieve a deadlock:

44

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Mutual Exclusion: At least one resource must be held in a non-sharable mode. If any other
process requests this resource, then that process must wait for the resource to be released.
Hold and Wait: A process must be simultaneously holding at least one resource and waiting for
at least one resource that is currently being held by some other process.
No preemption: Once a process is holding a resource ( i.e. once its request has been granted ),
then that resource cannot be taken away from that process until the process voluntarily releases
it.
Circular Wait: A set of processes { P0, P1, P2, . . ., PN } must exist such that every P[ i ] is
waiting for P[ ( i + 1 ) % ( N + 1 ) ].

25) What is Banker's algorithm?


Banker's algorithm is used to avoid deadlock. It is the one of deadlock-avoidance method. It is
named as Banker's algorithm on the banking system where bank never allocates available cash
in such a manner that it can no longer satisfy the requirements of all of its customers.

26) What is the difference between logical address space and physical address space?
Logical address space specifies the address that is generated by CPU. On the other hand,
physical address space specifies the address that is seen by the memory unit.

27) What is fragmentation?


Fragmentation is a phenomenon of memory wastage. It reduces the capacity and performance
because space is used inefficiently.

28) How many types of fragmentation occur in Operating System?


There are two types of fragmentation:
Internal fragmentation: It is occurred when we deal with the systems that have fixed size
allocation units.
External fragmentation: It is occurred when we deal with systems that have variable-size
allocation units.

29) What is spooling?


Spooling is a process in which data is temporarily gathered to be used and executed by a device,
program or the system. It is associated with printing. When different applications send output
to the printer at the same time, spooling keeps these all jobs into a disk file and queues them
accordingly to the printer.

30) What is the difference between internal commands and external commands?
Internal commands are the built-in part of the operating system while external commands are
the separate file programs that are stored in a separate folder or directory.

31) What is semaphore?


Semaphore is a protected variable or abstract data type that is used to lock the resource being
used. The value of the semaphore indicates the status of a common resource.

45

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

There are two types of semaphore:


Binary semaphores and Counting semaphores.

32) What is a binary Semaphore?


Binary semaphore takes only 0 and 1 as value and used to implement mutual exclusion and
synchronize concurrent processes.

33) What is Belady's Anomaly?


Belady's Anomaly is also called FIFO anomaly. Usually, on increasing the number of frames
allocated to a process virtual memory, the process execution is faster, because fewer page faults
occur. Sometimes, the reverse happens, i.e., the execution time increases even when more
frames are allocated to the process. This is Belady's Anomaly. This is true for certain page
reference patterns.

34) What is starvation in Operating System?


Starvation is Resource management problem. In this problem, a waiting process does not get
the resources it needs for a long time because the resources are being allocated to other
processes.

35) What is aging in Operating System?


Aging is a technique used to avoid the starvation in resource scheduling system.

36) What are the advantages of multithreaded programming?


A list of advantages of multithreaded programming:
Enhance the responsiveness to the users.
Resource sharing within the process.
Economical
Completely utilize the multiprocessing architecture.

37) What is the difference between logical and physical address space?
Logical address specifies the address which is generated by the CPU whereas physical address
specifies to the address which is seen by the memory unit.
After fragmentation

38) What are overlays?


Overlays makes a process to be larger than the amount of memory allocated to it. It ensures
that only important instructions and data at any given time are kept in memory.

39) When does trashing occur?


Thrashing specifies an instance of high paging activity. This happens when it is spending more
time paging instead of executing.

46

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

40) What is a Batch Operating System?


Batch Operating System is a type of Operating System which creates Batches for the execution
of certain jobs or processes.
The Batches contains jobs of such a kind that the jobs or processes which are very similar in
the procedure to be followed by the jobs or processes. The Batch Operating System has an
operator which performs these tasks.
An operator groups together comparable jobs or processes that have the same criteria into
batches. The operator is in charge and takes up the job of grouping jobs or processes with
comparable requirements.
Batch Operating System follows First Come First Serve principle.

41) Do the Batch Operating System interact with Computer for processing the needs of jobs or
processes required?
No, this is not that kind of Operating Systems which tries to interact with the computer. But
this job is taken up by the Operator present in the Batch Operating Systems.

42) What are the advantages of Batch Operating System?


Advantages of Batch Operating System:
The time which the Operating System is at rest is very small or also known as Idle Time for
the Operating System is very small.
Very big tasks can also be managed very easily with the help of Batch Operating Systems
Many users can use this Batch Operating Systems.
It is incredibly challenging to estimate or determine how long it will take to finish any task.
The batch system processors are aware of how long a work will take to complete when it is in
line.

43) What are the disadvantages of Batch Operating System?


Disadvantages of Batch Operating System:
If any work fails in the Batch Operating System, the other jobs will have to wait for an
indeterminate period of time.
Batch Operating systems are very challenging to debug,
Batch Operating Systems can be expensive at times
The computer operators who are using Batch Operating Systems must to be knowledgeable
with batch systems.

44) Where is Batch Operating System used in Real Life


They are used in Payroll System and for generating Bank Statements.

45) What is the Function of Operating System?


The most important functions of Operating Systems are:
File Management, Job Management, Process Management, Device Management and Memory
Management.

47

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

46) What are the Services provided by the Operating System?


The services provided by the Operating Systems are:
Security to your computer
Protects your computer from external threats
File Management
Program Execution
Helps in Controlling Input Output Devices
Useful in Program Creation
Helpful in Error Detection
Operating System helps in communicating between devices
Analyzes the Performance of all devices

47) What is a System Call in Operating Systems?


Programs can communicate with the operating system by making a system call. When a
computer application requests anything from the kernel of the operating system, it performs a
system call. System call uses Application Programming Interfaces (API)to deliver operating
system services to user programs.

48) What are the Types of System Calls in Operating Systems?


The System Calls in Operating Systems are:
Communication, Information Maintenance, File Management, Device Management, and
Process Control

49) What are the functions which are present in the Process Control and File Management
System Call?
The Functions present in Process Control System Calls are:
Create, Allocate, Abort, End, Terminate and Free Memory.

50) What are the functions which are present in the File Management System Call?
The Functions present in File Management System Calls are:
Create, Open, Read, Close and Delete.

51) What is a Process in Operating Systems?


A process is essentially software that is being run on the Operating System. The Process is a
Procedure which must be carried out in a sequential manner.
The fundamental unit of work that has to be implemented in the system is called a process.
An active program known as a process is the basis of all computing. Although relatively similar,
the method is not the same as computer code. A process is a "active" entity, in contrast to the
program, which is sometimes thought of as some sort of "passive" entity.

52) What are the Classical Problems of Process Synchronization?


The Classical Problems of Process Synchronization are:
Bound Buffer Problem or Consumer Producer Problem

48

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

Dining Philosopher's Problem


Readers and writers Problem
Sleeping Barber Problem.

53) What is Process Control Block (PCB)?


A data structure called a Process Control Block houses details about the processes connected
to it. The term "process control block" can also refer to a "task control block," "process table
entry," etc.
As data structure for processes is done in terms of the Process Control Block (PCB), it is crucial
for process management. Additionally, it describes the operating system's present condition.

54) What are the Data Items in Process Control Block?


The Data Items in Process Control Block are:
Process State, Process Number, Program Counter, Registers, Memory Limits and List of Open
Files.

55) What are the Files used in the Process Control Block?
The Files used in Process Control Block are:
Central Processing Unit (CPU) Scheduling Information
Memory Management Information
Accounting Information
Input Output Status Information

56) What are the differences between Thread and Process?


Thread Process
Threads are executed within the same Processes are executed in the different memory
process spaces
Threads are not independent of each other Processes are independent of each other

57) What are the advantages of Threads in Operating Systems?


The advantages of Threads in Operating System are:
Threads are executed very faster than Switches
Threads ensure that the communication between threads are very easier
The Throughput of the system is increased if the process is divided into multiple threads
When a thread in a multi-threaded process completes its execution, its output can be returned
right away.

58) What are the disadvantages of Threads in Operating Systems?


The disadvantages of Threads in Operating System are:
The code becomes more challenging to maintain and debug as there are more threads.
The process of creating threads uses up system resources like memory and CPU.
Because unhandled exceptions might cause the application to crash, we must manage them
inside the worker method.

49

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)


lOMoARcPSD|40571466

59) What are the types of Threads in Operating System?


The types of Threads in Operating System are:
User Level Threads and Kernel Level Threads.

60) What is Process Scheduling in Operating Systems?


The task of the process manager that deals with removing the active process from the CPU and
choosing a different process based on a certain strategy is known as process scheduling.

61) What are types of Process Scheduling Techniques in Operating Systems?


The types of Process Scheduling Techniques in Operating Systems are:
Pre Emptive-Process Scheduling and Non-Pre Emptive-Process Scheduling

62) What is Context Switching?


Context switching is a technique or approach that the operating system use to move a process
from one state to another so that it can carry out its intended function using system CPUs.

63) What is Process Synchronization in Operating Systems?


Process synchronization, often known as synchronization, is the method an operating system
uses to manage processes that share the same memory space. By limiting the number of
processes that may modify the shared memory at once via hardware or variables, it helps ensure
the consistency of the data.

64) What are the Operations in Semaphores?


The Operations in Semaphores are:
Wait or P Function () and Signal or V Function ()

65) What is the use of Dispatcher in Operating Systems?


After the scheduler completes the process scheduling, a unique application called a dispatcher
enters the picture. The dispatcher is the one who moves a process to the desired state or queue
once the scheduler has finished its selection task. The module known as the dispatcher is what
grants a process control over the CPU once the short-term schedule has chosen it.

66) How can we avoid Deadlock?


We can avoid Deadlock by using Banker's Algorithm.

67) What are Page Replacement Algorithms in Operating Systems?


The Page Replacement Algorithms in Operating Systems are:
First In First Out
Optimal
Least Recently Used
Most Recently Used

50

Downloaded by Sana Saleem (sbunnypk47b@gmail.com)

You might also like