Operating System Master Copy
Operating System Master Copy
DATA SCIENCE
LAB MANUAL
MASTER COPY
DEPARTMENT OF ARTIFICIAL INTELLIGENCE
AND DATASCIENCE
Year : III
Semester : VI
Regulation : 2021
2. Problem analysis Identify, formulate, review research literature, and analyze complex
engineering prob- lems reaching substantiated conclusions using first principles of
Mathematics, natural sciences, and engineering sciences
3. Design/developmen t Design solutions for complex engineering problems and design system
ofsolutions components orprocesses that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal,
and environmental considerations
4. Conduct investigations of Use research-based knowledge and research methods including design of
complex problems experiments, analysis and interpretation of data, and synthesis of the information to
provide valid
conclusions
5. Modern tool usage Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professionalengineering practice.
7. Environment and Understand the impact of the professional engineering solutions in societal
sustain- ability: and environ- mental contexts, and demonstrate the knowledge of, and need for
sustainable develop- ment.
8. Ethics Apply ethical principles and commit to professional ethics and responsibilities
andnorms of the engineering practice.
9. Individual and team work Function effectively as an individual, and as a member or leader in diverse teams,
and inmultidisciplinary settings.
10. Communication Communicate effectively on complex engineering activities with the engineering
com- munity and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give
and receive
clear instructions.
11. Project management Demonstrate knowledge and understanding of the engineering and management
andfinance princi- ples and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary
environments.
12. Life-long Learning Recognize the need for, and have the preparation and ability to engage in
independentand life-long learning in the broadest context of technological change.
Course Objectives
OB1: To understand the basics and functions of operating systems.
OB2: To understand Processes and Threads.
OB3: To analyze Scheduling algorithms and process synchronization.
OB4: To understand the concept of Deadlocks.
OB5: To analyze various memory management schemes.
OB6: To be familiar with I/O management and File systems.
OB7: To be familiar with the basics of virtual machines and Mobile OS like iOS and Android.
Course outcome
At the end of the course, the student should be able to:
CO4 Explain the functionality of file systems I/O systems, and Virtualization L4
CO-PO, PSO Correlation Matrix: (3- > Strong, 2- > Moderate, 1 – >| Low)
CO- P P P P P P P P P PO PO PO PS PS PS
P O O O O O O O O O 10 11 12 O1 O2 O3
O, 1 2 3 4 5 6 7 8 9
P
S
O
3 1 1 1 - - - - 1 1 1 2 2 1 2
CO1
2 3 1 3 1 - - - 3 2 2 3 3 3 1
CO2
2 2 3 3 2 - - - 3 3 1 2 1 1 1
CO3
2 2 1 1 3 - - - 1 1 2 1 1 1 2
CO4
2 3 3 1 3 - - - 3 2 2 1 3 1 2
CO5
CO–POMAPPINGWITHEXPERIMENTS
Course Program
S. Topic
Outcome Outcome
No.
Process Management using System Calls : Fork, Exec, Getpid, Exit, Wait,
3.
Close CO2 1,2,3,4,5,9
3 Process Management using System Calls : Fork, Exit, Getpid, Wait, Close 13
Write C programs to implement the various CPU Scheduling Algorithms
4 18
Syllabus
1. Installation of Operating system : Windows/ Linux
2. Illustrate UNIX commands and Shell Programming
3. Process Management using System Calls : Fork, Exec, Getpid, Exit, Wait, Close
4. Write C programs to implement the various CPU Scheduling Algorithms
5. Illustrate the inter process communication strategy
6. Implement mutual exclusion by Semaphores
7. Write a C program to avoid Deadlock using Banker's Algorithm
8. Write a C program to Implement Deadlock Detection Algorithm
9. Write C program to implement Threading
10.Implement the paging Technique using C program
11.Write C programs to implement the following Memory Allocation Methods
a. First Fit
b. Worst Fit
c. Best Fit
12.Write C programs to implement the various Page Replacement Algorithms
13.Write C programs to Implement the various File Organization Techniques
14.Implement the following File Allocation Strategies using C programs
a. Sequential
b. Indexed
c. Linked
15.Write C programs for the implementation of various disk scheduling algorithms
COURSE OBJECTIVES:
OUTCOMES:
Upon successful completion of this course, the students will be able to:
CO1: Apply the concepts of operating systems in various computing systems.
CO2 : Analyze various scheduling algorithms and process synchronization, deadlock,
prevention and avoidance algorithms.
CO3 : Apply various memory management schemes for memory allocation.
CO4 : Elucidate the functionality of file systems I/O systems, and Virtualization
CO5 : Compare iOS and Android Operating Systems
CO6 : Apply the various scheduling concepts for a real time problem.
CO-PO MAPPING
Aim:
To install windows operating system any guest operating system like Linux using VMware.
Output:
a)Process of installing linux in VMware:
1. Click Create a New Virtual Machine
2. Select the default option, Installer disc image file (iso)
3. Click Browse to find the ISO file
4. With "guest" OS selected, click Next
5. Select Linux as the Guest operating system type
6. Under Version, scroll through the list and select the OS
7. Click Next to proceed and if necessary, input a Virtual machine name
8. Confirm the storage Location and change if needed
9. With the operating system selected and configured, it's time to build the virtual machine.
a. Under Specify Disk Capacity adjust Maximum disk size if required (the default should
be enough)
b. Select Split virtual disk into multiple files as this makes moving the VM to a new PC easy
c. Click Next then confirm the details on the next screen
d. If anything seems wrong click Back, otherwise click Finish
10.End the process
Output:
Result:
ThustheWindows operating system has been installed standalone and linux operating system
has been installed in VMware successfully.
VivaQuestions
1. Define Operating System.
2. Where OS resides in sysem?
3. What do you meant by BIOS?
4. Difference between CLI and GUI.
5. List the purpose of Operating System.
6. State the purpose of VMware.
7. What is virtualization?
8. Differentiate type1 and tyep2 virtualization.
9. What do you meant by VMM?
7
Ex.No:2
Illustrate UNIX commands and Shell Programming
Date:
Aim:
To illustrate UNIX commands and Shell Programming.
Program:
who
The ‘$ who’ command displays all the users who have logged into the system currently. The thing tty2 is
terminal line the user is using and the next line gives the current date and time
$ who
Output:gomathynayagam tty2 2024-03-25 09:32 (:0)
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).
$ pwd
Output: /home/Documents
cal
The ‘$ cal’ means calendar and it simply display calendar on to your screen.
$ cal
Output : March 2024
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 16 27 28 29 30
31
grep
grep is an acronym for ‘globally search a regular expression and print it’.The ‘$ grep’ command searches
the specified input fully(globally) for a match with the supplied pattern and displays it.
Man
The ‘$ man’ command stands for ‘manual’ and it can display the in-built manual for most of the
commands that we ever need. In the above example, we can read about the ‘$ pwd’ command.
$ man pwd
passwd
The ‘$ passwd’ command simply changes the password of the user.
$ passwd
clear
The ‘$ clear’ command is used to clean up the terminal
$ clear
8
ls
The ‘ls’ command simply displays the contents of a directory.
$ ls
Output: Desktop Documents Downloads Music Pictures Public Scratch Templates Videos
mkdir
The ‘$ mkdir’ stands for ‘make directory’ and it creates a new directory.
$ mkdirnewfolder
rmdir
The ‘$ rmdir’ command deletes any directory we want to delete.
$ rmdirnewfolder
cd
The ‘$ cd’ command stands for ‘change directory’ and it changes your current directory to some other
directory.
$ cd newfolder
cp
This ‘$ cp ‘ command stands for ‘copy’ and it simply copy/paste the file wherever you want.
$ cp /home/harssh/file.txt /home/harssh/new/
mv
The ‘$ mv’ command stands for ‘move’ and it simply move a file from a directory to another directory.
$ mv /home/harssh/file.txt /home/harssh/new
cat
Make a text file on Linux
$ cat > filename.txt
chmod
The ‘$ chmod’ command stands for change mode command.As there are many modes in Unix that can be
used to manipulate files in the Unix environment.Basically there are 3 modes that we can use with the
‘chmod’ command
∙ +w (stands for write and it changes file permissions to write)
$ chmod +w file.txt
$ chmod +r file.txt
$ chmod +x file.txt
9
rm
The rm command removes the entries for a specified file, group of files, or certain select files from a list
within a directory
$ rm file.txt
fold
fold command wraps each line in an input file to fit a specified width and prints it to the standard
output. rit@rit-OptiPlex-3010:~$ vi
c.txtrit@rit-OptiPlex-3010:~$
cat c.txtGoodMorningto all
helloeveryone
rit@rit-OptiPlex-3010:~$
fold c.txtGoodMorningto all
helloeveryone
rit@rit-OptiPlex-3010:~$ fold -w 10
c.txtGoodMorni
ng to
allhello
everyon
e
Output
Enter a number 3
6
2.Greatest of three
numbers Algorithm:
Step 1.Get three numbers. Say num1, num2, num3
Step2.If (num1 >num2)and(num1 > num3)
displaynum1
Step 3. elif(num2 > num1) and (num2 > num3)
displaynum2
Step4.Otherwise,
displaynum3
Program:
echo "EnterNum1"
10
read num1
echo "Enter Num2"
read num2
echo "Enter Num3"
read num3
echo "The greatest of three numbers:"
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ] then
echo $num1
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ] then
echo $num2
else
echo $num3
fi
Output:
Enter Num1 3
Enter Num2 7
Enter Num3 5
Thegreatest of threenumbers:7
Output:
EnteraNumber: 5
Numberis odd
Output:
Enter Size(N) 5
Enter Numbers 1
2
3
4
5
15
5.Arithmetic
Operations:
Algorithm:
Step1.Get two numbers.
Step2. Find the sum of two numbers and display the result.
Step 3. Find the difference between two numbers and display the result.
Step4. Find the product two numbers and displaythe result.
Step5: Divide the numbers and display the result.
Step6: Find the remainder using modulo operator and display the result.
Program:
echo "enter two numbers"
read a
read b
result=`expr $a + $b`
echo $result
result=`expr $a - $b`
echo $result
result=`expr $a \* $b`
echo $result
result=`expr $a / $b`
echo $result
result=`expr $a % $b`
echo $result
Output
enter two numbers 9 5
14S
4
45
1
4
VivaQuestions
1. DefineProcess.
2. Whatarethestates of aprocess?
3. Listthepurposeof OperatingSystem.
4. Statethe purposeofls command.
5. NamefewUnixCommands.
12
Ex.No:3
Process Management using System Calls : Fork, Exit,
Date: Getpid, Wait, Close
Aim:
To write C programs to demonstrate various system calls: Fork, Exit, Getpid, Wait, Close
Algorithm:
Output:
rit@rit-OptiPlex-3010:~/Documents$ sudo vim
fork.c rit@rit-OptiPlex-3010:~/Documents$make
fork rit@rit-OptiPlex-3010:~/Documents$/.fork
int main()
{
Int cpid;
if(fork() ==0)
exit(0); /* terminate child
*/ else
cpid=wait(NULL); /*reapingparent*/
return0;
}
/*
Output:
rit@rit-OptiPlex-3010:~/Documents
$ gccwaittest.crit@rit-OptiPlex-
3010:~/Documents$./a.out
Parent pid =
5508Childpid=5509
*/
14
intmain()
{
char *binaryPath =
"/bin/ls"; char*arg1 ="-lh";
char*arg2= "/home";
execl(binaryPath,binaryPath,arg1,arg2,NULL);
return0;
}
Output:
rit@rit-OptiPlex-3010:~/Documents$
gccexecltest.crit@rit-OptiPlex-3010:~/Documents
$
./a.out
total28K
drwxr-xr-x2endsemendsem4.0KApr252019endse
m drwxr-xr-x2login login4.0K Apr25 2019login
drwx------2rootroot
16KJul92018lost+found drwxr-xr-x22 rit rit
4.0K Jan3 11:56rit
#include <unistd.h>
int main()
{
char *programName = "ls";
char *arg1 = "-l";//-lh
char *arg2= "/home";
execlp(programName,programName,arg1, arg2,NULL);
return0;
}
Output
rit@rit-OptiPlex-3010:~/Documents$
gccexeclptest.crit@rit-OptiPlex-3010:~/Documents
$
./a.out
total28
drwxr-xr-x2endsemendsem4096Apr252019endse
m drwxr-xr-x2loginlogin4096 Apr252019login
drwx------2rootroot16384Jul 92018lost+found
drwxr-xr-x22 rit rit 4096 Jan3 11:56 rit
#include <stdio.h>
#include<dirent.h
> int main(void)
{
structdirent *de;// Pointer fordirectoryentry
// opendir() returns a pointer of DIR type.DIR*dr =opendir(".");
{
printf("Could not open current directory" );
return0;
}
//Referhttp://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
//forreaddir()
while ((de = readdir(dr)) !=
NULL)
printf("%s\n",de->d_name);
closedir(dr);
return0;
}
Output:
rit@rit-OptiPlex-3010:~/Documents
$ gccdirectorytest.crit@rit-OptiPlex-
3010:~/Documents$./a.out
a.outdirectory
test.c
.
..
forktest.ce
x
ittest.cexec
l
ptest.cexec
l test.c
#include <stdio.h>
#include
<sys/stat.h>
#include<stdlib.h>
int main()
{
char *fd = "forktest.c";
structstat *buf;
stat(fd,buf);
Output
Program using open and close system call
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
//if filedoes nothavein directory
//thenfilefoo.txtiscreated.
int fd = open("foo.txt", O_RDONLY | O_CREAT);printf("fd=%d\n", fd);
if(fd==-1)
{
// print which type of error have in a code
printf("Error Number%d\n", errno);
int i =
close(fd);
return0;
}
Result:
VivaQuestions:
1. Definefork.
2. Whataresystemcalls?
3. Namesomefilemanagementsystemcalls.
4. Statevarious typesof system calls.
5. Howdoesa userprogramcommunicate withOS?
Ex.No:4
Write C programs to implement the various CPU Scheduling
Date: Algorithms
Aim:
To write C programs to implement various CPU Scheduling algorithms.
Algorithm:
FCFS
1.Initialize arrays to store the process‘s parameters like process id, arrival time, burst time,
completion time, turnaround time and waiting time
2.Get the number of processes from the user, n.
3.For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4. Calculate completion time, cti, turnaround time, tati and waiting time, wti for all the
processes, i. Completion Time:
ct0 = at0 + bt0 ;
when i>=1,
cti = cti-1 + bti ;
Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
5. Display the average turnaround time, avgtat and average waiting time,avgwt of the
processes using FCFS scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;
SJF (Non-pre-emptive)
1.Initialize arrays to store the process‘s parameters like process id, arrival time, burst time,
completion time, turnaround time and waiting time
2.Get the number of processes from the user, n.
3.For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4. Select and sort the processes based on the minimum arrival time and minimum Burst
time for execution.
5. Calculate completion time, cti, turnaround time, tati and waiting time, wti for all the
processes, i. Completion Time:
ct0 = at0 + bt0 ;
when i>=1,
cti = cti-1 + bti ;
Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
6. Display the average turnaround time, avgtat and average waiting time, avgwt of the
processes using SJF non-pre-emptive scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;
SJF (Pre-emptive)
1.Initialize arrays to store the process‘s parameters like process id, arrival time, burst time,
completion time, turnaround time and waiting time
2.Get the number of processes from the user, n.
3.For each process i, get the process id, pidi, arrival time, ati and burst time, bti.
4.Until all processes get completely executed,
Initialize current_time = 0 and store the remaining time of processes.
At every single process‘s arrival (time) ati, find process with minimum remaining time among the
processes that arrives till the current_time and reduce its remaining time by 1.
Check if the process‘s remaining time becomes 0.
Increment the counter of process completion, cti.
Completion time of current process, cti = current_time + 1
5. Calculate turnaround time, tati and waiting time, wti for all the
processes, i. Turnaround Time:
tati = cti - ati ;
totaltat+= tati ;
Waiting Time:
wti = tati - bti ;
totalwt+= wti ;
6. Display the average turnaround time, avgtat and average waiting time, avgwt of the processes
using SJF pre-emptive scheduling algorithm.
Average Turnaround Time:
avgtat = totaltat / n ;
Average Waiting Time:
avgwt = totalwt / n ;
Program Code:
FCFS
#include<stdio.h>
int main()
{
int bt[10],at[10];
double ct[10],wt[10],tat[10];
int n,sum=0;
float totaltat=0,totalwt=0;
printf("Enter number of processes");
scanf("%d",&n);
printf("Enter arrival time & burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of the process %d",i+1);
scanf("%d",&at[i]);
printf("Burst time of process %d",i+1);
scanf("%d",&bt[i]);
printf("\n");
}
for(int j=0;j<n;j++)
{
sum+=bt[j];
ct[j]+=sum;
}
for(int k=0;k<n;k++)
{
tat[k]=ct[k]-at[k];
totaltat=totaltat+tat[k];
}
double avgtat=totaltat/n;
for(int k=0;k<n;k++)
{
wt[k]=tat[k]-bt[k];
totalwt=totalwt+wt[k];
}
double avgwt=totalwt/n;
printf("\t\t SOLUTIONS:\n\n");
printf("P#\tAT\tBT\tCT\t\tTAT\t\tWT\t\n\n");
for(int i=0;i<n;i++)
{
printf("p%d\t%d\t%d\t%f\t%f\t%f\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\nAverage TurnaroundTime=%f\n",avgtat);
printf("Average wt=%f\n",avgwt);
return 0;
}
SOLUTIONS:
P# AT BT CT TAT WT
Average TurnaroundTime=27.000000
Average wt=17.000000
SJF Preemptive
#include<stdio.h>
int main()
{
int bt[10],at[10],temp[10];
double ct[10],wt[10],tat[10];
int n,sum=0,curntime,complete=0,small;
float totaltat=0,totalwt=0;
printf("Enter number of processes");
scanf("%d",&n);
printf("Enter arrival time & burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of the process %d:",i+1);
scanf("%d",&at[i]);
printf("Burst time of process
%d:",i+1); scanf("%d",&bt[i]);
printf("\n");
temp[i]=bt[i];
}
bt[9]=9999;
for(curntime=0;complete!=n;curntime++)
{
small=9;
for(int i=0;i<n;i++)
{
if(at[i]<=curntime && bt[i]<bt[small] && bt[i]>0)
{
small=i;
}
}
bt[small]--;
if(bt[small]==0)
{
complete++;
ct[small]=curntime+1;
tat[small]=ct[small]-at[small];
totaltat+=tat[small];
wt[small]=tat[small]-temp[small]
;
totalwt+=wt[small];
}
}double avgwt=totalwt/n;
double avgtat=totaltat/n;
for(int i=0;i<n;i++)
{
printf("p%d\t%d\t%d\t%f\t%f\t%f\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\nAverage TurnaroundTime=%f\n",avgtat);
printf("Average wt=%f\n",avgwt);
}
Average TurnaroundTime=13.000000
Average wt=6.500000
SJF Non-preemptive
#include<stdio.h>
int main()
{
int BT[10]={0},AT[10]={0},TAT[10]={0},WT[10]={0},CT[10]={0};
int i,j,n,sum=0;
float tatsum=0,wtsum=0;
float avgtat=0,avgwt=0;
printf("Enter number of
process:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter arrival and burst time of %d",i+1);
scanf("%d%d",&AT[i],&BT[i]);
}
CT[0]=AT[0]+BT[0];
for(i=1;i<n;i++)
{
CT[i]=CT[i-1]+BT[i];
}
for(i=0;i<n;i++)
{
TAT[i]=CT[i]-AT[i];
WT[i]=TAT[i]-BT[i];
tatsum+=TAT[i];
wtsum+=WT[i];
}
printf("\n\nSOLUTION:\n");
printf("p\tAT\tBT\tCT\tTAT\tWT\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\t%d\t%d\t%d\n",i+1,AT[i],BT[i],CT[i],TAT[i],WT[i]);
}
printf("Average Turnaround Time: %f",tatsum/n);
printf("\n");
printf("Average Waiting Time:
%f",wtsum/n); return 0;
}
SOLUTION:
p AT BT CT TAT WT
1 0 7 7 7 0
2 0 5 12 12 7
3 0 1 13 13 12
4 0 2 15 15 13
5 0 8 23 23 15
Average Turnaround Time:
14.000000 Average Waiting Time:
9.400000
Priority
#include<stdio.h>
void sort(int b[],int a[],int n[],int p[], int m)
{
int i,j,s,tmp;
for(i=0;i<m;i++)
{
for(j=i+1;j<m;j++)
{
if(p[i]>p[j])
{
tmp=p[i];p[i]=p[j];p[j]=tmp;
tmp=b[i];b[i]=b[j];b[j]=tmp;
tmp=a[i];a[i]=a[j];a[j]=tmp;
tmp=n[i];n[i]=n[j];n[j]=tmp;
}
}
}
}
int main()
{
int AT[10]={0},BT[10]={0},PID[10]={0};
int WT[10]={0},TAT[10]={0},PR[10]={0},CT[10]={0};
int i,j,n,sum=0;
float tatsum=0,wtsum=0;
float avgtat=0,avgwt=0;
printf("Enter number of
process:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter arrival and burst time and priority of %d",i+1);
scanf("%d%d%d",&AT[i],&BT[i],&PR[i]);
}
sort(BT,AT,PID,PR,n);
CT[0]=AT[0]+BT[0];
for(i=1;i<n;i++)
{
CT[i]=CT[i-1]+BT[i];
}
for(i=0;i<n;i++)
{
TAT[i]=CT[i]-AT[i];
WT[i]=TAT[i]-BT[i];
tatsum+=TAT[i];
wtsum+=WT[i];
}
printf("\n\nSOLUTION:\n");
printf("p\tAT\tBT\tPR\tCT\tTAT\tWT\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n",i+1,AT[i],BT[i],PR[i],CT[i],TAT[i],WT[i]);
}
printf("Average Turnaround Time: %f",tatsum/n);
printf("\n");
printf("Average Waiting Time: %f",wtsum/n);
return 0;
}
SOLUTION:
p AT BT PR CT TAT WT
1 0 1 1 1 1 0
2 0 5 2 6 6 1
3 0 10 3 16 16 6
4 0 1 4 17 17 16
5 0 2 4 19 19 17
Average Turnaround Time:
11.800000 Average Waiting Time:
8.000000
Round Robin
#include<stdio.h>
int main()
{
int count,j,n,time,remain,flag=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count
]); wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count]
; flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
return 0;
}
Enter Total Process: 3
Enter Arrival Time and Burst Time for Process Process Number 1
:0 5
Enter Arrival Time and Burst Time for Process Process Number 2
:1 7
Enter Arrival Time and Burst Time for Process Process Number 3
:3 4
Enter Time Quantum: 2
P[3] | 9 | 5
P[1] | 13 | 8
P[2] | 15 | 8
Result:
Thus the CPU scheduling algorithms have been implemented and tested successfully.
Viva Questions:
1. What do you mean by CPU Scheduling?
2. What is preemptive and nonpreemptive scheduling?
3. What is turnaround time?
4. What is dispatch latency?
5. Define race condition.
28
Ex.No:5
Illustrate the inter process communication strategy
Date:
Aim
To implement interprocess communication using pipe and shared memory
i) Interprocess Communication using pipe
System calls used:
fork() - To create child
process.fork() returns :
<0 fail to create child (new) process
=0 for child process
>0 i.e process ID of the child process to the parent process. When >0 parent process will execute.
pipe()
pipe() is used for passing information from one process to another. pipe() is unidirectional
therefore, for two-way communication between processes, two pipes can be set up, one for each
direction.
Algorithm pass a string between parent and child process through pipe
Inside Child Process :
1. Child process closes the reading end of the pipe (fd[0])
2. Child process writes a string and passes the string to parent process via pipe‘s writing end
(fd[1])
3. Child process exits.
Algorithm to generate numbers in parent process and and determine if it is odd or even in child
process through pipe
Header file:
#include<sys/ipc.h>
#include<sys/shm.h>
2. shmat()
To attach the shared memory segment identified by shmid to the address space of the
calling process.
Header file
#include <sys/shm.h>
Prototype
void *shmat(int shmid, const void *shmaddr, int shmflg)
shmat() attaches the shared memory segment identified by shmid to the address space of the
calling process. The attaching address is specified by shmaddr with one of the following criteria:
If shmaddr is NULL, the system chooses a suitable (unused) address atwhich to attach the
segment.
If shmaddr is not NULL and SHM_RND is specified in shmflg, the attachment occurs at the
address equal to shmaddr rounded down to the nearest multiple of SHMLBA.
Field Description
Is a unique positive integer created by a shmget system call and
shmid
associated with a segment of shared memory.
shmaddr Points to the desired address of the shared memory segment
Specifies a set of flags that indicate the specific shared memory
shmflg
conditions and options to implement
30
return address at which segment was attached to the process, or
value -1 on error
3. shmdt
The shmdt() function detaches from the calling process's data segment the shared memory
segmentlocated at the address specified by shmaddr.
Header File
include <sys/shm.h>
Prototype
int shmdt(const void *shmaddr)
Field Description
4. shmctl
Perform shared memory control operations
Header File
#include <sys/shm.h>
Prototype
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
Field Description
Is a unique positive integer created by a shmget system call and
shmid
associated with a segment of shared memory.
Points to the data structure used for sending or receiving data during
buf
execution of shared memory control operations
return
If successful, shmctl() returns zero. On failure, it returns -1
value
/* Send
"string"
through the
} output side
else of pipe */
{ write(fd[1],
string,
(strlen(strin
g)+1));
exit(0);
}
/* Parent
process
closes up
output side
of pipe */ readbuffer,
close(fd[1] sizeof(read
); buffer));
printf("Rec
/* Read in a string from the pipe */ eived
nbytes = string: %s",
read(fd[0], readbuffer)
;
return(0);
}
Output:
Received string: Hello!
Program for odd or even:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int i, fd[2], nbytes;
pid_t childpid;
int a[10],b[10];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
for(i=0;i<10;i++)
{
a[i]=i+1;
}
}
else
{
w
r
i
t
e
(
f
d
[
1
]
,
a
,
1
0
*
s
i
z
e
o
f
(
i
n U
t L
) L
) )
; ;
e c
x l
i o
t s
( e
0 (
) f
; d
w [
a 1
i ]
t )
( ;
N nbytes = read(fd[0], b, 10*sizeof(int));
for(i=0;i<10;i++)
{
if(b[i]%2==0)
{
printf("%d is even number\n",b[i]);
}
else
{
printf("%d is odd number\n",b[i]);
}
}
}
return(0);
}
Output:
1 is odd number
2 is even
number3 is odd
number 4
is even number
5 is odd number
6 is even
number7 is odd
number 8 is even
number9 is odd
number
10 is even number
for(i=0;i<10;i++)
{
s
h
} m
p
} t
else r
{ [
i
]
=
'
a
'
+
i
;
p
u
t m
c p
h t
a r
r [
( i
s ]
h )
;
printf("\n\n%s",shmptr);wait(NULL);
shmid = shmget(2041,32,0666);
shmptr = shmat(shmid,0,0); printf("Child is reading\n");
for(i=0;i<10;i++)
{
putchar(shmptr[i]);
}
Output
Parent is writing
abcdefghij
Child is reading
abcdefghij
Result:
Viva Questions:
35
Ex.No:6
Implement mutual exclusion by Semaphore
Date:
Aim:
To write C program to implement Producer Consumer problem using semaphores.
2. semctl
Used to perform control operations on a semaphore set.
Prototype
int semctl ( int semid, int semnum, int cmd, union semun arg )
Field Description
semid Is the semaphore identifier.
semnum Is a semaphore number greater than zero and less than sem_nsems.
3. semop()
Perform array of operations on semaphore set
Header files
#include <sys/sem.h>
Prototype
int semop(int semid, struct sembuf *sops, size_t nsops)
Field Description
sops
Points to the array of semaphore-operation structures.
ALGORITHM:
Step 1: The Semaphore mutex, full & empty are initialized.
Step 2: Use fork system call to create two processes namely Producer process and Consumer process
Step 3: In the case of producer process,
i)Produce an item into temporary variable.
ii)If there is empty space in the buffer, check the mutex value to enter into the critical section.
iii)If the mutex value is 0, allow the producer to add value in the temporary variable to the buffer.
(iv) Signal the mutex value and increase the full value by 1.
Step 4: In the case of consumer process,
i)It should wait if the buffer is empty
ii) If there is any item in the buffer, check for mutex value, if the mutex==0, remove item
from buffer
iii)Signal the mutex value and reduce the empty value by 1.
iv)Consume the
item.
Step 5: Print the
result
Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<sys/sem.h>
void semAcquired(int);
void semReleased(int);
void main() {
char c[10];
int mutex, empty, full, pid, shmid; int in = -1, out = -1;
char *buffer;
mutex = semget(IPC_PRIVATE,1,0666);
if(mutex == -1) {
perror("Failed to create semaphre...\n");
exit(0);
}
if(semctl(mutex, 0, SETVAL, 1) == -1) {
perror("Failed to set mutex value...\n");
exit(0);
}
empty = semget(IPC_PRIVATE, 1, 0666 | IPC_CREAT);
if(empty == -1) {
perror("Error while creating Empty...\n");
exit(0);
}
if(semctl(empty, 0, SETVAL, 50) == -1) {
perror("Failed to set Empty value...\n");
exit(0);
}
full = semget(IPC_PRIVATE, 1, 0666 | IPC_CREAT);
if(full == -1) {
perror("Failed to create full...\n");
exit(0);
}
if(semctl(full, 0, SETVAL, 0) == -1) {
perror("Failed to set full value...\n");
exit(0);
}
shmid = shmget(IPC_PRIVATE, 50*sizeof(char), 0666 | IPC_CREAT);
buffer = shmat(shmid, 0, 0);
pid = fork();
do {
if(pid == -1) {
perror("Error creating consumer...\n");
exit(0);
}
elseif(pid == 0) {
printf("Enter Item produced : ");
scanf("%s", c);
semAcquired(empty);
semAcquired(mutex);
in = (in + 1) % 50;
buffer[in] = c[0];
semReleased(full);
semReleased(mutex);
}
else { s
l
e
e
p
(
3
)
;
} s
}while(1); e
} m
A
c
q
u
i
r
e
d
(
f
u
l
l
)
;
s
e
m
A
c
q
u
i
r
e
d
(
m
u
t
e
x
)
;
o
u
t
=
(
o
u
t
+
1
)
%
5
0
;
c su
[ me
0 d
] no
= w...
b \n",
u c[0]
f );
f sem
e Rel
r eas
[ ed(
o mut
u ex);
t sem
] Rel
; eas
prin ed(
tf(" em
%c pty)
con ;
void semAcquired(int semid) {
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1;
sb.sem_flg = 0;
if(semop(semid, &sb, 1) == -1) {
perror("Failed to acquire semaphores...\n");
exit(0);
}
}
void semReleased(int semid) {
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = 1;
sb.sem_flg = 0;
if(semop(semid, &sb, 1) == -1) {
perror("Failed to release semaphores...\n");
exit(0);
}
}
OUTPUT:
Enter Item produced : a
a consumed now...
Enter Item produced : r
r consumed now...
Result:
Thus the program to implement semaphores has been executed successfully.
Viva Questions:
1. Define busy waiting and spinlock
2. Name some synchronization problem.
3. Define Semaphore.
4. State the advantages of Semaphores.
5. What is a monitor?
39
Ex.No:7
Write C programs to avoid Deadlock using Banker's Algorithm
Date:
Aim:
To write a C program to implement Banker‘s Algorithm for Deadlock Avoidance.
Program Code:
#include <stdio.h>
#include
<stdlib.h> int
main() {
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10],
safeSequence[10]; int p, r, i, j, flag, count;
count = 0;
// Calculating need.
for(i = 0; i < p; i++)
for(j = 0; j < r; j++)
need[i][j] = Max[i][j] - alloc[i][j];
do {
flag = -1;
for(i = 0; i < p; i++) {
// If not completed
if(completed[i] == 0) {
flag = i ;
for(j = 0; j < r; j++) {
if(avail[j] < need[i][j]) {
flag = -1;
break;
}
}
}
if(flag != -1)
break;
}
if(flag != -1) {
safeSequence[count] = flag + 1;
count++;
for(j = 0; j < r; j++) {
avail[j] += alloc[flag][j];
alloc[flag][j] = 0;
Max[flag][j] = 0;
completed[flag] = 1;
}
}
}while(count != p && flag != -1);
if(count == p) {
printf("\nThe system is in a safe state...\n");
printf("Safe Sequence : < ");
41
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state...");
}
42
OUTPUT:
Viva Questions:
1. Define request edge and assignment edge.
2. What are the methods for handling deadlocks?
3. Define deadlock prevention.
4. Define deadlock avoidance.
5. Define request edge and assignment edge.
6. What are conditions under which a deadlock situation may arise?
43
Ex.No:8
Write a C program to Implement Deadlock Detection Algorithm
Date:
Aim:
To write C program to implement Deadloack detection algorithm.
DataStructuresNeeded:
● Available
o Vector of length m
o Indicates number of available resources of each type.
● Allocation
o Matrix of size n*m
o A[i,j] indicates the number of jth resource type allocated to ith process.
● Request
o Matrix of size n*m
o Indicates requet of each process.
o Request[i,j] tells number of instance Pi process is request of jth resource type.
Algorithm
Step1
1. Let Work(vector) length = m
2. Finish(vector) length = n
3. InitializeWork = Available.
1. For i=0, 1, …., n-1, if Allocationi = 0, then Finish[i] = true; otherwise,
Finish[i]=false.
Step2
1. Findanindexisuch thatboth
1. Finish[i]==false
2. Requesti<=
WorkIf no such i exists go to
step 4.Step 3
1. Work=Work+Allocationi
2.Finish[i]=
trueGo to
Step
2.Step 4
If Finish[i]== false for some i, 0<=i<n, then the system is in a deadlocked state.
Moreover,ifFinish[i]==false the process Pi is deadlocked.
Program Code
#include<stdio.h>
static int finish[20];
inti,j,np,nr;
int main()
{
int alloc[10][10],request[10][10],avail[10],r[10],w[10];
printf("\nEnter the no of process: ");
scanf("%d",&np);
printf("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr;i++)
44
{
printf("\nTotal Amount of the Resource R%d: ",i+1);
scanf("%d",&r[i]);
}
printf("\nEnter the request matrix:");for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&request[i][j]);
for(i=0;i<np;i++)
{
int
count=0;for(j=0;
j<nr;j++)
{
if(alloc[i][j]==0)
count++;
else
break;
}
if(count==nr)
finish[i]=1;
}
//initializeW with avail
for(j=0;j<nr;j++)
w[j]=avail[j];
OUTPUT:
46
Entertheallocation matrix:
10110
11000
00010
00000
Deadlock detected
Result:
VivaQuestions
1. Define deadlock detection.
2. State Deadlock recovery
3. What are the methods for handling deadlocks?
4. Define deadlock avoidance.
5. List out the scheduling algorithms
47
Ex.No:9
Write C program to implement Threading
Date:
Aim:
To write programs to implement threading.
Description
1. Thread synchronization is defined as a mechanism which ensures that two or more
concurrentprocesses or threads do not simultaneously execute some particular program segment
known ascriticalsection.
2. Processes‘access to critical section is controlled by using synchronization techniques.
3. When one thread starts executing the critical section (serialized segment of the program)
the other thread should wait until the first thread finishes.
4. If proper synchronization techniques are not applied, it may cause a race condition where
the values ofvariables may be unpredictable
5. A Mutex is a lock that we set before using a shared resource and release after using it.
6. When the lock is set, no other thread can access the locked region of code. So this ensures
asynchronized access of shared resources in the code.
Algorithm
1.Create two threads
2.Let the threads share a common resource, say counter
3. Even if thread2 si scheduled to start while thread was not done, access to shared
resource is not done as it is locked by mutex
4.Once thread1 completes,thread2 starts execution
5.Stop
Program Code:
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int counter = 0;
pthread _ttid[2];
pthread _mutex_tlock;
pthread _mutex_unlock(&lock);
void main()
{
int i = 0;
48
int error;
while(i< 2)
{
error= pthread_create(&tid[i],NULL,&test,NULL);
if(error!=0)
{
printf("Threadcan't becreated:%s\n",strerror(error));
}
i++
OUTPUT:
Job1 started
Job 1 finished
Job2 started
Job 2 finished
//MutexLock-SineandCosine
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int counter = 0;
pthread_ttid[2];
pthread_mutex_t lock;
void main()
{ int i = 0;
int error;
if(pthread_mutex_init(&lock, NULL) != 0) {
printf("Mutex init failed...\n");
exit(1);
}
while(i< 2) {
error = pthread_create(&tid[i], NULL, &test, NULL);
if(error != 0) {
printf("Thread can't be created : %s\n", strerror(error));
}
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock)
;
}
OUTPUT
Job1 started
Enter a number :
90Sinof90is:1.00000
0 Job 1 finished
Job2 started
Enteranumber: 90
Cosof 90 is : 0.000000
Job 2 finished
Result:
Aim:
Algorithm:
1.Get the process size from the user.
2.Get the page size.
3.Calculate the no.of pages needed.
4.Enter page table details
5.Get the page number and offset value and find the corresponding frame number.
6.Display the physical memory address
Program Code:
#include<stdio.h>
#include<math.h>
void main()
{
double npages;
int n,ps,pn,off,fnumber,m,i;
int pagetable[100];
printf("enter process size");
scanf("%d",&ps);
printf("\nenter page size");
scanf("%d",&m);
npages=ceil(ps/m);
n=npages;
printf("\nenter page table details");
for(i=0;i<n;i++)
{
scanf("%d",&pagetable[i]);
}
printf("\nenter page number");
scanf("%d",&pn);
printf("\nenter offset");
scanf("%d",&off);
printf("\npagetable");
printf("\npage number frame number");
for(i=0;i<n;i++)
{
printf("\n");
printf("%d\t%d",i,pagetable[i]);
}
fnumber=pagetable[pn];
printf("\nframe number offset
value:");
printf("%d%d",fnumber,off);
printf("\nThe corresponding physical address is %d",(fnumber*m)+off);
}
VirtualmemorySimulator
Explanation
$Page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.
$page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.
$page fault occurs but our physical pages are empty. So we don't need to find any victim page from
physical memory.
$hey! It's a page hit our virtual page(6) maps to physical page(2).
$ page fault occurs but our physical memory is full now. so we have to find an victim page from
physical memory to replace it with our current virtual page(4). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 3 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.
$hey! It's a page hit our virtual page(1) maps to physical page(0).
$ page fault occurs but our physical memory is full now.so we have to find an victim page
fromphysical memory to replace it with our current virtual page(0). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 2 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.
$ page fault occurs but our physical memory is full now.so we have to find an victim page
fromphysical memory to replace it with our current virtual page(3). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 1 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.
$ page fault occurs but our physical memory is full now. so we have to find an victim page from
physical memory to replace it with our current virtual page(5). now to find victim page we apply our
page replacement policy this time it is fifo. By this policy victim page found is 3 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.
$ hey! It's a page hit our virtual page(1) maps to physical page (0).Hey! It's a page hit our virtual page(5)
maps to physical page(3).
$ page fault occurs but our physical memory is full now.so we have to find an victim page from
physical memory to replace it with our current virtual page(2). now to find victim page we apply
ourpage replacement policy this time it is fifo. By this policy victim page found is 1 which is not dirty.
Sowe don't require to copy it back on disk. Now it's over, we just have to replace this victim page with
our virtual page.
53
Result:
Thus the program has been executed and Virtual memoryhas been simulated.
VivaQuestions:
1. What is Paging?
2. Define Page Table.
3. What is Fragmentation?
4. State Segmentation.
Ex.No:11 Write C programs to implement the following Memory Allocation
Date: Methods
a. First Fit
b. Worst Fit
C. Best Fit
Aim
To allocate memory requirements for processes using the first-fit, best-fit, or worst-fit strategy
isusedto select a freeholefrom theset ofavailableholes.
Firstfit
● Allocate the first hole that is big enough.
● Searching starts from the beginning of set of holes.
Algorithm
1.Get number of holes/partitions, say m.
2.Get the size of each hole/partition.
3.Get number of processes, say n.
4.Get the memory requirements for each process.
5.Allocate processes to holes,by examining each holeas follows:
a.If holesize>process size then
i.Mark process as allocated to that hole.
ii.Decrement hole size by processs size.
b.Otherwise check the next from these tof holes
6.Print the list of process and their allocated holes or unallocated status.
7.Print the list of holes,their actual and current availability.
8.Stop
Bestfit
● Allocate the smallest hole that is big enough.
● The list of free holes is kept sorted according to size in ascending order.
Algorithm
1.Get number of holes, say m.
2.Getthe size of each hole
3.Get number of processes, say n.
4.Get the memory requirements for each process.
5.Allocate processes to holes,by examining each hole as follows:
a.Sortthe holes according to their sizes in ascending order
b.If holesize>process size then
i.Mark process as allocated to that hole.
ii.Decrement hole size by processsize.
c.Otherwise check the next from the set of sortedholes
6.Print the list of process and their allocated holes or unallocated status.
7.Print the list of holes,their actual and current availability.
8.Stop
Worst fit
● Allocate the largest hole.
● The list of free holes is kept sorted according to size in descending order.
Algorithm
1.Get number of holes, say m.
2.Get the sizeof each hole
3.Get number ofprocesses, sayn.
4.Get the memory requirements for each process.
5.Allocate processes to holes,by examining each hole as follows:
a.Sort the holes according to their sizes in descending order
b.If hole size>process size then
i.Mark process as allocated to that hole.
ii.Decrement hole sizebyprocesssize.
c.Otherwise check the next from theset of sorted holes
6.Print the list of process and their allocated holes or unallocated status.
7.Print the list of holes,their actual and current availability.
8.Stop
Program Code
#include<stdio.h>
void main()
{
int memory[50], process[50], i, j, p, m, assign[50], r[50];
printf("Enter number of memory partitions and processes : ");
scanf("%d%d",&m,&p);
printf("Size of all memory spaces : \n");
for(i=0; i<m; i++)
{
printf("Partition%d:",(i+1));
scanf("%d", &memory[i]);
r[i] =memory[i];
}
}
printf("Proc\tSize\tAssignment\n");
for(i=0; i<p; i++)
{
printf("%d\t%d\t%d\n",(i+1),process[i],assign[i]);
}
printf("Hole\tSize\tRemain\n");
for(j=0; j <m; j++)
{
printf("%d\t%d\t%d\n",(j+1),r[j],memory[j]);
}
}
OUTPUT:
//BestFit
#include<stdio.h>
void main()
{
int i,j,n,m,a[10],b[10],c[10],min;
printf("enter the no of processes");
scanf("%d",&n);
printf("enter the no.of holes");
scanf("%d",&m);
printf("Enter the processes");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the holes");
for(j=0;j<m;j++)
{
scanf("%d",&b[j]);
}
i=0,j=0;
printf("processes\tprocessessize\tholes" );
for(i=0;i<n;i++)
{
min=0;
for(j=0;j<m;j++)
{
if(b[j]<b[min]&&a[i]<=b[min])
{
min=j;
}
}
b[min]=b[min]-a[i];
printf("\n%d\t%d\t%d\t",i,a[i],min+1);
}
printf("Remaining holesize\n");
for(j=0;j<m;j++)
{
printf("\n%d",b[j]);
}
}
OUTPUT:
enter the no of processes2
enter the no.of holes3
Entertheprocesses
100
200
Enter the holes
300
400
500
processes processessize holes
0 100 1
1 200 1
Remaining
holesize0
400
500
// Worst Fit
#include<stdio.h>
void main()
{
int i,j,n,m,a[10],b[10],c[10],max;
printf("enter the no of processes");
scanf("%d",&n);
printf("enter the no.of holes");
scanf("%d",&m);
printf("Enter the processes");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the holes");
for(j=0;j<m;j++)
{
scanf("%d",&b[j]);
}
i=0,j=0;
printf("processes\tprocessessize\tholes" );
for(i=0;i<n;i++)
{
max=0;
for(j=0;j<m;j++)
{
if(b[j]>b[max]&&a[i]<=b[max])
{
max=j;
}
}
b[max]=b[max]-a[i];
printf("\n%d\t%d\t%d\t",i,a[i],max+1);
}
printf("Remaining holesize\n");
for(j=0;j<m;j++)
{
printf("\n%d",b[j]);
}
}
OUTPUT:
processes processes
size holes
0 100 3
1 200 3
Remaining hole size
300
400
300
Result:
The programs have been implemented and executed successfully.
VivaQuestions:
1. Define logical address and physical address.
2. What is logical address space and physical address space?
3. What is the main function of the memory-management unit?
4. What are the common strategies to select a free hole from a set of available holes?
5. What do you mean by best fit?
6. What do you mean by first fit?
61
Ex.No:12 Implement the various Page Replacement Algorithms
Date:
Aim:
To write a C program to implement FIFO page replacement algorithm.
ALGORITHM:
1. Read the size of the frame, no. of elements and elements one by one.
2. Initialize the frames with value-1.
3. Insert each element in to frame, if it ‘s already not present.
4. If the frame is full and the new element is not already present, then replace the
oldest element by the new element.
5. Increment no.of page faults by one while inserting each element into the frames.
6. Display the contents of frames during processing and the total no. of page faults.
PROGRAM:
#include <stdio.h>
#include <conio.h>
int
refstr[50],cq[10];
int f=0,r=0,pf=0,nof,len;
int check(int);
void addq(int);
int main()
{
int temp,i,count,p,f1;
printf("\n\n\tFIFO PAGE REPLACEMENT ALGORITHM\n\n");
printf("Enter the no of frames\n");
scanf("%d",&nof);
printf("\nEnter the number of
elements\n"); scanf("%d",&len);
for(count=0;count<nof;count++)
cq[count]=-1;
printf("\nEnter the elements\n");
for(i=0;i<len;i++)
scanf("%d",&refstr[i]);
count=0;
printf("\n\t CONTENTS OFFR A MES DURING PROCESSING\n\n");
for(i=0;i<nof;i++)
printf("F[%d]\t",i);
printf("Page
fault\n"); do
{
p=refstr[count];
f1=check(p);
if(f1==0)
62
{
addq(p);
pf+=1;
}
count+=1;
for(i=0;i<nof;i++)
printf("%d\t",cq[i]);
if(f1==0)
printf("*\n");
else
printf("-\n");
}while(count<len);
printf("\nNoofpagefaults:%d\n",pf);
}
int check(intx)
{
int i;
for(i=0;i<r;i++)
if(cq[i]==x)
return(1);
return(0);
}
void addq(int x)
{
if(r==nof)
{
cq[f]=
x; f++;
}
else
{
cq[r]=x
; r++;
}
}
OUTPUT
1-1 -1 PFNo. 1
12 -1 PFNo. 2
12 3 PFNo. 3
4 23 PFNo. 4
5 23 PFNo. 5
523
523
52 1 PFNo. 6
52 4 PFNo. 7
52 3 PFNo. 8
Total number of page faults- -8
Result:
Viva Questions:
1. What is virtual memory?
2. Define effective access time.
3. What is the basic approach of page replacement?
4. What are the various spage replacement algorithms used for page replacement?
5. What are the major problems to implement demand paging?
Ex.No:13 File Organization Techniques
Date:
Aim:
Description:
The directory structure is the organization of files into a hierarchy of folders.In a single-level directory
system, all the files are placed in one directory. There is a root directory which has all files.It has a
simple architecture and there are no sub directories. Advantage of single level directory system is that
it is easy to find a file in the directory. In the two-level directory system, each user has own user file
directory (UFD). The system maintains a master block that has one entry for each user.This master
block contains the addresses of the directory of the users.When a user job starts or a user logs in,the
system's master file directory(MFD)is searched.When a user refers to a particular file,only his own
UFD is searched.This effectively solves the name collision problem and isolates users from one
another. Hierarchical directory structure allows users to create their own sub directories and to
organize their files accordingly. A tree is the most common directory structure. The tree has a root
directory,and every file in the system has a unique path name. A directory (or subdirectory) contains a
set of files or subdirectories.
13.1 SingleLevelDirectory
AIM:
To write a c program to implement the single level directory file organization.
PROGRAM:
#include <stdio.h>
#include<string.h>
int main()
{
char d[20];
charf[20][20];
int
i,j,nfiles,flag;
chartemp[20];
printf("enter names of the master directory:");
scanf("%s",d);
printf("enter size of directory:");
scanf("%d",&nfiles);
printf("enter the file names :");
scanf("%s",f[0]);
for(i=1;i<nfiles;)
{
scanf("%s",temp);
j=0; flag=0;
while(j<i)
{
if((strcmp(f[j],temp))==0)
{
printf("Overwritingexistingfile!");
flag=1
; break;
}j+
+;
}
if(flag==0)
{
strcpy(f[i],temp);
i++;
}
}
printf("\n");
printf(" directory\tsize\n");
printf("************************\n");
printf("%s\t\t%2d\n",d,nfiles);
printf("Files in the directory\n");
printf("************************\n");
for(i=0;i<nfiles;i++)
{
printf("%s\n",f[i]);
}
}
Output:
enter names of the master directory:
root enter size of directory:4
enter the file names
:iij
j jj
Over writing existing
file!kk
ll
directory size
***********************
* root 4
Files in the directory
************************
ii
jj
k
kl
l
13.2. Two Level Directory
AIM:
To write a c program to implement the two level directory file organization.
PROGRAM:
#include<stdio.h>
struct st
{
char dname[10];
char
fname[10][10]; int
ds;
}dir[10];
void main()
{
int i,j,k,n;
printf("enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter directory %d names:",i+1);
scanf("%s",dir[i].dname);
printf("enter size of directories:");
scanf("%d",&dir[i].ds);
printf("enter file names:");
for(j=0;j<dir[i].ds;j++)
{
scanf("%s",dir[i].fname[j]);
}
}
printf("\ndirname\t\tsize\t\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d\t\t",dir[i].dname,dir[i].ds)
; for(j=0;j<dir[i].ds;j++)
{
printf("%s\t",dir[i].fname[j]);
printf("\n\t\t\t\t");
}
printf("\n");
}
}
Output
enter number of directories:2
enter directory 1 names:user2
enter size of directories:2
enter file names:cat
test
enter directory 2 names:user3
enter size of directories:1
enter file names:at
user3 1 at
Description:
Hierarchical directory structure allows users to create their own sub directories and to organize their
files accordingly. A tree is the most common directory structure. The tree has a root directory, and
every file in the system has a unique pathname. A directory (or subdirectory) contains a set of files or
sub directories.
13.3 HierarchicalLevelDirectory
AIM:
To write a c program to implement the hierarchical level directory file organization.
ALGORIHTM:
Step1.Start
Step2. Define structure and declare structure variables
Step3.Start main and declare variable
Step4.Create a directory tree structure
Step5.Display the directory tree in graphical mode
Step6. Get the names of the root directory and files are organized with this
directoryStep7.Stop the program
PROGRAM:
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct
tree_element*link[5];
};
type def struct tree_elementnode;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
init graph(&gd,&gm,"c:\tc\BGI");
display(root);
getch();
closegraph();
}
GraphAIM:
To writea c program to implement the directed acyclic graph of file organization.
ALGORIHTM:
Step1.Start
Step2. Define structure and declare structure variables
Step3.Start main and declare variable
Step4.Create a directory tree structure
Step5. Display the directory tree in graphical mode
Step6. Get the names of the root directory and files are organized with this graph structure.
Step7.Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
structtree_element
charname[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element*link[5];
};
typedef struct tree_elementnode;
typedef struct
{
char
from[20];
char to[20];
}link;
Link
L[10]; int
nofl; node *
root; void
main()
{
int gd=DETECT,gm;
root=NULL;clrscr();
create(&root,0,"root",0,639,320)
; read_links();
clrscr();
initgraph(&gd,&gm,"c:\tc\BGI")
; draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
int i;
printf("how many links");
scanf("%d",&nofl);
for(i=0;i<nofl;i++)
printf("File/dir:");
fflush(stdin);
gets(L[i].from);
printf("user
name:");
fflush(stdin);
gets(L[i].to);
}
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
}
search(node*root,char*s,int*x,int*y)
{
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
{
*x=root->x;
*y=root->y;
return;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y)
;
}
}
}
create(node**root,intlev,char*dname,intlx,intrx,intx)
{
int i,gap;
if(*root==NULL)
(*root)=(node*)malloc(sizeof(node));
printf("enter name of dir/file(under
%s):",dname); fflush(stdin);
gets((*root)->name);
printf("enter 1 for dir/ 2 for
file:");
scanf("%d",&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50
; (*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++
)
(*root)->link[i]=NULL
; if((*root)->ftype==1)
{
printf("no of sub directories /files (for
%s):",(*root)->name);
scanf("%d",&(*root)->nc);if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++
)
create( &((*root)->link[i] ),lev+1, (*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
Else
(*root)->nc=0;
}
}
/* displays the constructed tree in graphics mode
*/display(node*root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}
OUTPUT
Result:
Thus,the programs have been executed successfully.
VivaQuestions:
DESCRIPTION:
Sequential allocation
● Each file in the disk occupies a contiguous address space on the disk.
● In this scheme, the address is assigned in the linear fashion.
● This is very easy to implement the contiguous allocation method.
● In the contiguous allocation technique, external fragmentation is a major issue.
Indexed allocation
● In this scheme, a special block known as the index block contains the pointer to all the
blocks occupied by a file.
● Each file contains its index which is in the form of an array of disk block addresses.
● The ith entry of index block point to the ith block of the file.
● The address of the index block is maintained by the directory.
● When we create a file all pointer is set to nil.
● A block is obtained from the free space manager when the first ith block is written.
● When the index block is very small it is difficult to hold all the pointers for the large file to
deal with this issue a mechanism is available.
Linked allocation
● In this scheme, disk blocks are arranged in the linked list form which is not contiguous.
● In this scheme, the directory entry contains the pointer of the first block and pointer of the
ending block.
● Each pointer contains the address of the next block.
● When we create a new file we simply create a new entry with the linked allocation.
● Each directory contains the pointer to the first disk block of the file.
● When the pointer is null then it defines the emptyfile.
PROGRAM:
#include<stdio.h>
void main()
{
int
n=0,i,j,b[20],sb,len,flag=0,t[20],x,c[20][20],y;
intdiskspace[50];//50 blocks
do
{
printf("Enter the starting block of file%d:",i+1);
scanf("%d",&sb);
printf("Enter no. of blocks(length) occupied by file%d:",i+1);
scanf("%d",&len);
for(j=sb;j<(sb+len);j++)
{
if(diskspace[j]==1)
{
printf("Space can't be allocated");
flag=1;
break;
}
}
if(flag==0)
{
t[n]=sb;
b[n]=len
; n++;
for(j=sb;j<(sb+len);j++)
{
diskspace[j]=1;
}
}
printf("\n Do you want to enter more files?(y-1/n-0)");
scanf("%d",&y);
flag=0;
}while(y==1);
printf("Filename\tStart\tLength\n");
for(i=0;i<n;i++)
printf("%d\t%d
\t%d\n",i+1,t[i],b[i]);
printf("Enterfilename:");
scanf("%d",&x);
printf("File name is:%d\n",x);
printf("length is:%d\n",b[x-1]);
printf("blocks occupied:");
for(i=t[x-1];i<(t[x-1]+b[x-1]);i++
)
printf("%4d",i);
Output:
}
Output:
Enter no.of files:1
Enter index block and size of index block1:198
Enter no. of blocks occupied by file1:5
Enter blocks of file1:9
16
1
10
25
File index length
1 19 5
Enter file name:1
file name is:1
Index is:19
Block occupied are:9161 1025-1 -1-1
#include<stdio.h>
struct file
{
Char fname[10];
int start,size,block[10];
}f[10];
void main()
{
int i,j,n;
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);
}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size)
; for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
}
}
Output:
Enter no. of files:1
Enter file name:jeep
Enter starting block:9
Enter no.of blocks:5
Enter block numbers:116
9
10
25
File start size block
Jeep 951--->16--->9--->10--->25
Result:
Thus the programs for File Allocation Strategies have been executed successfully.
Viva Questions
Aim:
To write C programs for the implementation of various disk scheduling algorithms.
Description:
Disk scheduling is done by operating systems to schedule I/O requests arriving for the disk. Disk
scheduling is also known as I/O scheduling.
Disk scheduling is important because:
● Multiple I/O requests may arrive by different processes and only one I/O request can be served at
a time by the disk controller. Thus other I/O requests need to wait in the waiting queue and need
to be scheduled.
● Two or more request may be far from each other so can result in greater disk arm movement.
● Hard drives are one of the slowest parts of the computer system and thus need to be accessed in
an efficient manner.
Disk Scheduling Algorithms:
1. First Come First Serve (FCFS)
FCFS is the simplest of all the Disk Scheduling Algorithms. In FCFS, the requests are addressed in
the order they arrive in the disk queue
ALGORITHM:
1. 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. Take the tracks one by one 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.
PROGRAM:
#include
<stdio.h>
#include
<math.h> int size
= 8;
void FCFS(int arr[],int head)
{
int seek_count = 0;
int cur_track, distance;
for(int i=0;i<size;i++)
{
cur_track = arr[i];
// calculate absolute distance
distance = fabs(head - cur_track);
// increase the total count
seek_count += distance;
// accessed track is now new head
head = cur_track;
}
printf("Total number of seek operations: %d\n",seek_count);
// Seek sequence would be the same
// as request array sequence
printf("Seek Sequence is\n");
for (int i = 0; i< size; i++) {
printf("%d\n",arr[i]);
}
}
//Driver code
int main()
{
// request array
int arr[8] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;
FCFS(arr,head);
return 0;
}
Output:
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114
PROGRAM:
#include<stdio.h>
#include<stdlib.h
> int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial,count=0;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
// logic for sstf disk scheduling
/* loop will execute until all process is completed*/
while(count!=n)
{
int
min=1000,d,index;
for(i=0;i<n;i++)
{
d=abs(RQ[i]-initial);
if(min>d)
{
min=d;
index=i
;
}
}
TotalHeadMoment=TotalHeadMoment+min;
initial=RQ[index];
// 1000 is for max
// you can use any
number RQ[index]=1000;
count++;
}
printf("Total head movement is %d",TotalHeadMoment);
return 0;
}
Output:
Enter the number of Request
8
Enter Request Sequence
95 180 34 119 11 123 62 64
Enter initial head Position
50
Total head movement is 236
3. SCAN (Elevator) algorithm:
In SCAN disk scheduling algorithm, head starts from one end of the disk and moves towards the
other end, servicing requests in between one by one and reach the other end. Then the direction of the
head is reversed and the process continues as head continuously scan back and forth to access the
disk.
ALGORITHM:
1. 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. 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.
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
<stdio.h>
#include
<math.h> int
main()
{
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;
}
}
}
for (i = 1, j = 0; j < temp1; i++, j++)
queue[i] = queue1[j];
queue[i] = max;
for (i = temp1 + 2, j = 0; j < temp2; i++, j++)
queue[i] = queue2[j];
queue[i] = 0;
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:
Enter the max range of disk
200
Enter the initial head position
50
Enter the size of queue request
8
Enter the queue of disk positions to be read
95 180 34 119 11 123 62 64
Disk head moves from 50 to 62 with seek 12
Disk head moves from 62 to 64 with seek 2
Disk head moves from 64 to 95 with seek 31
Disk head moves from 95 to 119 with seek 24
Disk head moves from 119 to 123 with seek 4
Disk head moves from 123 to 180 with seek 57
Disk head moves from 180 to 200 with seek 20
Disk head moves from 200 to 34 with seek 166
Disk head moves from 34 to 11 with seek 23
Disk head moves from 11 to 0 with seek 11
Total seek time is 350
Average seek time is 43.750000
ALGORITHM:
1. Request array represents an array storing indexes of tracks that have been requested in
2. Ascending order of their time of arrival. ‘head’ is the position of disk head.
3. The intial direction in which head is moving is given and it services in the same direction.
4. The head services all the requests one by one in the direction head is moving.
5. The head continues to move in the same direction untill all the request in this direction are
6. not finished.
7. While moving in this direction calculate the absolute distance of the track from the head.
8. Increment the total seek count with this distance.
9. Currently serviced track position now becomes the new head position.
10.Go to step 5 until we reach at last request in this direction.
11.If we reach where no requests are needed to be serviced in this direction reverse the
12.Direction and go to step 3 until all tracks in request array have not been serviced.
PROGRAM:
#include<stdio.h>
#include<stdlib.h
> int main()
{
int
RQ[100],i,j,n,TotalHeadMoment=0,initial,size,move;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
printf("Enter total disk size\n");
scanf("%d",&size);
printf("Enter the head movement direction for high 1 and for low 0\n");
scanf("%d",&move);
}
}
int index;
for(i=0;i<n;i++)
{
if(initial<RQ[i])
{
index=i
; break;
}
}
// if movement is towards high value
if(move==1)
{
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];
}
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];
}
}
// if movement is towards low value
else
{
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];
}
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial)
; initial=RQ[i];
}
}
Output:
Enter the number of Request
8
Enter the Requests Sequence
95 180 34 119 11 123 62 64
Enter initial head position
50
Enter the head movement direction for high 1 and for low 0
1
Total head movement is 299