OS CSBS Lab programs-2023-05-24T04-28-15.434Z
OS CSBS Lab programs-2023-05-24T04-28-15.434Z
OS CSBS Lab programs-2023-05-24T04-28-15.434Z
1 Study of UNIX OS
Date :
Aim
To introduce the concepts of UNIX Operating System
Operating System
An Operating System is a set of programs that:
o Functions as an virtual machine by presenting an interface that is easier to program than the underlying
hardware
o Acts as resource management through orderly and controlled allocation of the processors, memories, and
I/O devices among the programs competing for it.
UNIX Features
1. Multi-user system—Multi-user capability of UNIX allows several users to use the same computer to
perform their tasks. Several terminals [Keyboards and Monitors] are connected to a single powerful server.
2. Multi-tasking system—Multitasking is the capability of the operating system to perform various task
simultaneously, i.e. a user can run multiple tasks concurrently.
3. Programming Facility—the UNIX shell has all the necessary ingredients like conditional and control
structures, etc.
4. Security—Every user must have a single login name and password. So, accessing another user’s data is
impossible without his permission.
Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and Libraries and
enhanced GUI (X Window).
Organization of UNIX
1. The kernel is the heart of the system, a collection of programs written in C that directly communicate with
the hardware. It manages the system resources, allocates time between user and processes, decides process
priorities, and performs all other tasks. The kernel, in traditional parlance, is often called the Operati ng
system.
2. The shell, on the other hand, is the "sleeping beauty" of UNIX. It is actually the interface between the user
and the kernel. The shell is the agency which takes care of the features of redirection and has a
programming capability of its own.
3. The Tools and Applications consist of Application Software, Compilers, Database Package, Internet tools,
UNIX commands, etc.
File System
All files in UNIX are related to one another. The file system of UNIX resembles a tree that grows
from top to bottom as shown in the figure. The file system begins with a directory called root (at the top).
The root directory is denoted by a slash (\). Branching from root there are several directories such as bin,
lib, etc, tmp, dev. Each of these directories contains several sub-directories and files.
Organization
File System
Result
Thus the study of UNIX Operating System has been completed successfully.
Exp. No. 2 Unix Commands
Date :
Aim
To study and execute Unix commands.
Login
Type telnet server_ipaddress in run window.
User has to authenticate himself by providing username and password. Once verified, a greeting and $
prompt appears. The shell is now ready to receive commands from the user. Options suffixed with a
hyphen (–) and arguments are separated by space.
General commands
Command Function
Date Used to display the current system date and time.
date +%D Displays date only
date +%T Displays time only
date +%Y Displays the year part of date
date +%H Displays the hour part of time
Cal Calendar of the current month
cal year Displays calendar for all months of the specified year
cal month year Displays calendar for the specified month of the year
Who Login details of all users such as their IP, Terminal No, User name,
who am i Used to display the login details of the user
Uname Displays the Operating System
uname –r Shows version number of the OS (kernel).
uname –n Displays domain name of the server
echo$HOME Displays the user's home directory
Bc Basic calculator. Press Ctrl+d to quit
lp file Allows the user to spool a job along with others in a print queue.
man cmdname Manual for the given command. Press q to exit
history To display the commands used by the user since log on.
exit Exit from a process. If shell is the only process then logs out
Directory commands
Command Function
Pwd Path of the present working directory
mkdir dir A directory is created in the given name under the current directory
mkdir dir1 dir2 A number of sub-directories can be created under one stroke
cd subdir Change Directory. If the subdir starts with / then path starts from root
(absolute) otherwise from current working directory.
cd To switch to the home directory.
cd / To switch to the root directory.
cd .. To move back to the parent directory
rmdir subdir Removes an empty sub-directory.
File commands
Command Function
cat > filename To create a file with some contents. To end typing press Ctrl+d. The >
symbol means redirecting output to a file. (< for input)
cat filename Displays the file contents.
cat>> filename Used to append contents to a file
cp src des Copy files to given location. If already exists, it will be overwritten
cp–i src des Warns the user prior to overwriting the destination file
cp –r src des Copies the entire directory, all its sub-directories and files.
mv old new To rename an existing file or directory. –i option can also be used
mv f1 f2 f3 dir To move a group of files to a directory.
mv –v old new Display name of each file as it is moved.
rm file Used to delete a file or group of files. –i option can also be used
rm * To delete all the files in the directory.
rm –r * Deletes all files and sub-directories
rm –f * To forcibly remove even write-protected files
Ls Lists all files and subdirectories (blue colored) in sorted manner.
ls name To check whether a file or directory exists.
ls name* Short-hand notation to list out filenames of a specific pattern.
ls –a Lists all files including hidden files (files beginning with .)
ls –x dirname To have specific listing of a directory.
ls –R Recursive listing of all files in the subdirectories
ls –l Long listing showing file access rights (read/write/execute-rwx for
user/group/others-ugo).
cmp file1 file2 Used to compare two files. Displays nothing if files are identical.
wc file It produces a statistics of lines (l), words(w), and characters(c).
chmod perm file Changes permission for the specified file. (r=4, w=2, x=1) chmod 740
file sets all rights for user, read only for groups and no rights for others
The commands can be combined using the pipeline (|) operator. For example, number of users logged in
can be obtained as.
who | wc -l
Finally to terminate the unix session execute the command exit or logout.
Output
$ date
Sat Apr 9 13:03:47 IST 2011
$ date +%D 04/09/11
$ date +%T 13:05:33
$ date +%Y 2011
$ date +%H 13
$ cal 08 1998
August 1998
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 26 27 28 29
30 31
$ who
root :0 Apr 9 08:41 vijai pts/0 Apr 9 13:00 (scl-64) cse4001 pts/3
Apr 9 13:18 (scl-41.smkfomra.com)
$ uname Linux
$ uname -r
2.4.20-8smp
$ uname -n localhost.localdomain
$ echo $HOME /home/vijai
$ echo $USER vijai
$ bc
3+5
8
$ pwd
/home/vijai/shellscripts/loops
$ mkdir filter $ ls filter list.sh regexpr shellscripts
$ cd shellscripts/loops/
$
$ cd $
$ cd /
[vijai@localhost /]$
[vijai@localhost /]$ cd /home/vijai/shellscripts/loops/
$ cd ..
[vijai@localhost shellscripts]$
$ rmdir filter $ ls list.sh regexpr shellscripts
$ cat > greet hi cse wishing u the
best
$ cat greet hi ece-a wishing u the
best
$ cat >> greet bye $ cat greet hi cse
wishing u the best bye
$ ls greet list.sh regexpr shellscripts
$ ls -a
. .bash_logout .canna .gtkrc regexpr .viminfo.tmp
.. .bash_profile .emacs .kde shellscripts .xemacs
.bash_history .bashrc greet list.sh .viminfo
$ ls -l
-rw-rw-r-- 1 vijai vijai 32 Apr 11 14:52 greet -rw-rw-r-- 1 vijai vijai 30 Apr 4
13:58 list.sh drwxrwxr-x 2 vijai vijai 4096 Apr 9 14:30 regexpr
$ cp greet ./regexpr/
$ ls greet list.sh regexpr shellscripts
$ ls ./regexpr demo greet
$ cp -i greet ./regexpr/ cp: overwrite 'greet'? n
$ mv greet greet.txt
$ ls greet.txt list.sh regexpr shellscripts
$ mv greet.txt ./regexpr/
$ ls
list.sh regexpr shellscripts
$ rm -i *.sh
rm: remove regular file 'fact.sh'? y rm: remove regular file
'prime.sh'? y
$ ls
list.sh regexpr shellscripts
$ wc list.sh
4 9 30 list.sh
$ wc -l list.sh 4 list.sh
$ cmp list.sh fact.sh list.sh fact.sh differ: byte 1, line 1
$ ls -l list.sh
-rw-rw-r-- 1 vijai vijai 30 Apr 4 13:58 list.sh
$ chmod ug+x list.sh
$ ls -l list.sh
-rwxrwxr-- 1 vijai vijai 30 Apr 4 13:58 list.sh
$ chmod 740 list.sh
$ ls -l list.sh
-rwxr----- 1 vijai vijai 30 Apr 4 13:58 list.sh
Result
Thus the study and execution of Unix commands has been completed successfully.
Exp. No. 3 Implementation of Unix System Calls
Date:
Aim:
Algorithm:
1. The processes executed in the user mode till the time a system call interrupts it.
2. After that, the system call is executed in the kernel-mode on a priority basis.
3. Once system call execution is over, control returns to the user mode.
Parameters should be pushed on or popped off the stack by the operating system.
Parameters can be passed in registers.
When there are more parameters than registers, it should be stored in a block, and the block address should
be passed as a parameter to a register.
Program:
cat
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[3] )
{
int fd,i;
char buf[2];
fd=open(argv[1],O_RDONLY,0777);
if(fd==-argc)
{
printf("file open error");
}
else
{
while((i=read(fd,buf,1))>0)
{
printf("%c",buf[0]);
}
close(fd);
}
}
Output:
student@ubuntu:~$gcc –o prgcat.out prgcat.c
student@ubuntu:~$cat > ff
hello
hai
student@ubuntu:~$./prgcat.out ff
hello
hai
ls
#include <sys/types.h>
#include <sys/dir.h>
#include <sys/param.h>
#include <stdio.h>
#define FALSE 0
#define TRUE 1
extern int alphasort();
char pathname[MAXPATHLEN];
main() {
int count,i;
struct dirent **files;
int file_select();
if (getwd(pathname) == NULL )
{
printf("Error getting pathn");
exit(0);
}
printf("Current Working Directory = %sn",pathname);
count = scandir(pathname, &files, file_select, alphasort);
if (count <= 0)
{
printf("No files in this directoryn");
exit(0);
}
printf("Number of files = %dn",count);
for (i=1;i<count 1; i)
printf("%s \n",files[i-1]->d_name);
}
int file_select(struct direct *entry)
{
if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0))
return (FALSE);
else
return (TRUE);
}
Output:
Student@ubuntu:~$ gcc list.c
Student@ubuntu:~$ ./a.out
Current working directory=/home/student/
Number of files=57
mv
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}
Output:
student@ubuntu:~$gcc –o mvp.out mvp.c
student@ubuntu:~$cat > ff
hello
hai
student@ubuntu:~$./mvp.out ff ff1
student@ubuntu:~$cat ff
cat:ff:No such file or directory
student@ubuntu:~$cat ff1
hello
hai
Result:
Thus the implementation of System call has been successfully done using C Language.
Exp. No. 4a FCFS Scheduling
Date:
Aim
To schedule snapshot of processes queued according to FCFS scheduling.
Process Scheduling
CPU scheduling is used in multi programmed operating systems.
By switching CPU among processes, efficiency of the system can be improved.
Some scheduling algorithms are FCFS, SJF, Priority, Round-Robin, etc.
Gantt chart provides a way of visualizing CPU scheduling and enables to understand better.
First Come First Serve (FCFS)
Process that comes first is processed first
FCFS scheduling is non-preemptive
Not efficient as it results in long average waiting time.
Can result in starvation, if processes at beginning of the queue have long bursts.
Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime for each process.
4. The wtime for first process is 0.
5. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
6. Compute average waiting time awat and average turnaround time atur
7. Display the btime, ttime and wtime for each process.
8. Display awat time and atur
9. Display GANTT chart for the above scheduling
10. Stop
Program
/* FCFS Scheduling - fcfs.c */
#include <stdio.h>
struct process
{
int pid;
int btime;
int wtime;
int ttime;
} p[10];
main() {
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ",(i+1));
scanf("%d", &p[i].btime);
p[i].pid = i+1;
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
Twat += p[i].wtime;
}
awat = (float)twat / n; atur = (float)ttur / n;
printf("\n F CFS Scheduling\n\n");
for(i=0; i<28; i++)
printf("-");
printf("\nProcess B-Time T-Time W-Time\n");
for(i=0; i<28; i++)
printf("-");
for(i=0; i<n; i++)
printf("\n P%d\t%4d\t%3d\t%2d",
p[i].pid,p[i].btime,p[i].ttime,p[i].wtime); printf("\n");
for(i=0; i<28; i++)
printf("-");
printf("\n\nAverage waiting time : %5.2fms", awat); printf("\nAverage turn around time : %5.2fms\n",
atur);
printf("\n\nGANTT Chart\n"); printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("|");
for(i=0; i<n; i++)
{
k = p[i].btime/2;
for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" "); printf("|");
}
printf("\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("0");
for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
}
Output
Enter no. of process : 4
Burst time for process P1 (in ms) : 10
Burst time for process P2 (in ms) : 4
Burst time for process P3 (in ms) : 11
Burst time for process P4 (in ms) : 6
FCFS Scheduling
Process B-Time T-Time W-Time
P1 10 10 0
P2 4 14 10
P3 11 25 14
P4 6 31 25
| P1 | P2 | P3 | P4 |
0 10 14 25 31
Result
Thus waiting time & turnaround time for processes based on FCFS scheduling was computed and the
average waiting time was determined.
Exp. No. 4b SJF Scheduling
Date:
Aim
To schedule snapshot of processes queued according to SJF scheduling.
Shortest Job First (SJF)
Process that requires smallest burst time is processed first.
SJF can be preemptive or non–preemptive
When two processes require same amount of CPU utilization, FCFS is used to break the tie.
Generally efficient as it results in minimal average waiting time.
Can result in starvation, since long critical processes may not be processed.
Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime for each process.
4. Sort the processes according to their btime in ascending order.
a. If two process have same btime, then FCFS is used to resolve the tie.
5. The wtime for first process is 0.
6. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
7. Compute average waiting time awat and average turn around time atur.
8. Display btime, ttime and wtime for each process.
9. Display awat and atur
10. Display GANTT chart for the above scheduling
11. Stop
Program
/* SJF Scheduling – sjf.c */
#include <stdio.h>
struct process
{
int pid;
int btime;
int wtime;
int ttime;
} p[10], temp;
main() {
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n); for(i=0; i<n; i++) {
printf("Burst time for process P%d (in ms) : ",(i+1));
scanf("%d", &p[i].btime);
p[i].pid = i+1;
}
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if((p[i].btime > p[j].btime) ||
(p[i].btime == p[j].btime && p[i].pid > p[j].pid))
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;
printf("\n S JF Scheduling\n\n"); for(i=0; i<28; i++)
printf("-");
printf("\nProcess B-Time T-Time W-Time\n");
for(i=0; i<28; i++)
printf("-");
for(i=0; i<n; i++)
printf("\n P%-4d\t%4d\t%3d\t%2d", p[i].pid,p[i].btime,p[i].ttime,p[i].wtime);
printf("\n");
for(i=0; i<28; i++)
printf("-");
printf("\n\nAverage waiting time : %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n|");
for(i=0; i<n; i++)
{
k = p[i].btime/2;
for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" ");
printf("|");
}
printf("\n-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n0");
for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
}
Output
Enter no. of process : 5
Burst time for process P1 (in ms) : 10
Burst time for process P2 (in ms) : 6
Burst time for process P3 (in ms) : 5
Burst time for process P4 (in ms) : 6
Burst time for process P5 (in ms) : 9
SJF Scheduling
Process B-Time T-Time W-Time
P3 5 5 0
P2 6 11 5
P4 6 17 11
P5 9 26 17
P1 10 36 26
| P3 | P2 | P4 | P5 | P1 |
0 5 11 17 26 36
Result
Thus waiting time & turnaround time for processes based on SJF scheduling was computed and
the average waiting time was determined.
Exp. No. 4c Priority Scheduling
Date:
Aim
To schedule snapshot of processes queued according to Priority scheduling.
Priority
Process that has higher priority is processed first.
Prioirty can be preemptive or non–preemptive
When two processes have same priority, FCFS is used to break the tie.
Can result in starvation, since low priority processes may not be processed.
Algorithm
1. Define an array of structure process with members pid, btime, pri, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime and pri for each process.
4. Sort the processes according to their pri in ascending order.
a.If two process have same pri, then FCFS is used to resolve the tie.
5. The wtime for first process is 0.
6. Compute wtime and ttime for each process as:
a.wtimei+1 = wtimei + btimei
b.ttimei = wtimei + btimei
7. Compute average waiting time awat and average turn around time atur
8. Display the btime, pri, ttime and wtime for each process.
9. Display awat and atur
10. Display GANTT chart for the above scheduling
11. Stop
Program
/* Priority Scheduling - pri.c */
#include <stdio.h>
struct process
{ int pid;
int btime; .
int pri;
int wtime;
int ttime;
} p[10], temp;
main() {
int i,j,k,n,ttur,twat; float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ", (i+1));
scanf("%d", &p[i].btime);
printf("Priority for process P%d : ", (i+1));
scanf("%d", &p[i].pri);
p[i].pid = i+1;
}
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if((p[i].pri > p[j].pri) ||(p[i].pri == p[j].pri && p[i].pid > p[j].pid) )
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
p[0].wtime = 0; for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;
printf("\n\t Priority Scheduling\n\n");
for(i=0; i<38; i++) printf("-");
printf("\nProcess B-Time Priority T-Time W-Time\n");
for(i=0; i<38; i++)
printf("-"); for (i=0; i<n; i++)
printf("\n P%-4d\t%4d\t%3d\t%4d\t%4d", p[i].pid,p[i].btime,p[i].pri,p[i].ttime,p[i].wtime); printf("\n");
for(i=0; i<38; i++)
printf("-");
printf("\n\nAverage waiting time : %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
printf("\n\nGANTT Chart\n");
printf("-");
Output
Enter no. of process : 5
Burst time for process P1 (in ms) : 10
Priority for process P1 : 3
Burst time for process P2 (in ms) : 7
Priority for process P2 : 1
Burst time for process P3 (in ms) : 6
Priority for process P3 : 3
Burst time for process P4 (in ms) : 13
Priority for process P4 : 4
Burst time for process P5 (in ms) : 5
Priority for process P5 : 2
Priority Scheduling
Process B-Time Priority T-Time W-Time
P2 7 1 7 0
P5 5 2 12 7
P1 10 3 22 12
P3 6 3 28 22
P4 13 4 41 28
-
Average waiting time : 13.80ms
Average turn around time : 22.00ms
GANTT Chart
| P2 | P5 | P1 | P3 | P4 |
0 7 12 22 28 41
Result
Thus waiting time & turnaround time for processes based on Priority scheduling was computed and
the average waiting time was determined.
Exp. No. 4d Round Robin Scheduling
Date:
Aim
To schedule snapshot of processes queued according to Round robin scheduling.
Round Robin
• All processes are processed one by one as they have arrived, but in rounds.
• Each process cannot take more than the time slice per round.
• Round robin is a fair preemptive scheduling algorithm.
• A process that is yet to complete in a round is preempted after the time slice and put at the end of
the queue.
• When a process is completely processed, it is removed from the queue.
Algorithm
1. Get length of the ready queue, i.e., number of process (say n)
2. Obtain Burst time Bi for each processes Pi.
3. Get the time slice per round, say TS
4. Determine the number of rounds for each process.
5. The wait time for first process is 0.
6. If Bi > TS then process takes more than one round. Therefore turnaround and waiting time should
include the time spent for other remaining processes in the same round.
7. Calculate average waiting time and turn around time
8. Display the GANTT chart that includes
a. order in which the processes were processed in progression of rounds
b. Turnaround time Ti for each process in progression of rounds.
9. Display the burst time, turnaround time and wait time for each process (in order of rounds they
were processed).
10. Display average wait time and turnaround time
11. Stop
Program
/* Round robin scheduling - rr.c */
#include <stdio.h>
main() {
int i,x=-1,k[10],m=0,n,t,s=0;
int a[50],temp,b[50],p[10],bur[10],bur1[10];
int wat[10],tur[10],ttur=0,twat=0,j=0;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d : ", (i+1));
scanf("%d", &bur[i]);
bur1[i] = bur[i];
}
printf("Enter the time slice (in ms) : ");
scanf("%d", &t);
for(i=0; i<n; i++)
{ b[i] = bur[i] / t;
if((bur[i]%t) != 0)
b[i] += 1;
m += b[i];
}
printf("\n\t\tRound Robin Scheduling\n");
printf("\nGANTT Chart\n");
for(i=0; i<m; i++) printf("--------"); printf("\n");
a[0] = 0;
while(j < m)
{
if(x == n-1)
x = 0;
else
x++;
if(bur[x] >= t)
{
bur[x] -= t;
a[j+1] = a[j] + t;
if(b[x] == 1)
{
p[s] = x;
k[s] = a[j+1];
s++;
}
j++;
b[x] -= 1;
printf(" P%d | ", x+1);
}
else if(bur[x] != 0)
{
a[j+1] = a[j] + bur[x];
bur[x] = 0;
if(b[x] == 1)
{
p[s] = x;
k[s] = a[j+1];
s++;
}
j++;
b[x] -= 1;
printf(" P%d |",x+1);
}
}
printf("\n"); for(i=0;i<m;i++)
printf("--------"); printf("\n");
for(j=0; j<=m; j++)
printf("%d\t", a[j]);
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(p[i] > p[j])
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
temp = k[i];
k[i] = k[j];
k[j] = temp;
}
}
}
for(i=0; i<n; i++)
{
wat[i] = k[i] - bur1[i];
tur[i] = k[i];
}
for(i=0; i<n; i++)
{
ttur += tur[i];
twat += wat[i];
}
printf("\n\n"); for(i=0; i<30; i++) printf("-");
printf("\nProcess\tBurst\tTrnd\tWait\n");
for(i=0; i<30; i++)
printf("-");
for (i=0; i<n; i++)
printf("\nP%-4d\t%4d\t%4d\t%4d", p[i]+1, bur1[i], tur[i],wat[i]);
printf("\n"); for(i=0; i<30; i++)
printf("-");
awat = (float)twat / n; atur = (float)ttur / n;
printf("\n\nAverage waiting time : %.2f ms", awat);
printf("\nAverage turn around time : %.2f ms\n", atur); }
Output
Enter no. of process : 5
Burst time for process P1 : 10
Burst time for process P2 : 29
Burst time for process P3 : 3
Burst time for process P4 : 7
Burst time for process P5 : 12
Enter the time slice (in ms) : 10
Round Robin Scheduling
GANTT Chart
P1 | P2 | P3 | P4 | P5 | P2 | P5 | P2 |
0 10 20 23 30 40 50 52 61
P1 10 10 0
P2 29 61 32
P3 3 23 20
P4 7 30 23
P5 12 52 40
Result
Thus waiting time and turnaround time for processes based on Round robin scheduling was computed and
the average waiting time was determined.
Exp. No. 5a Producer – Consumer Problem
Date:
AIM: To Write a C program to simulate the concept of Producer – Consumer Problem.
ALGORITHM
1. Define the maximum buffer size.
2. Enter the number of producers and consumers.
3. The producer produces the job and put it in the buffer.
4. The consumer takes the job from the buffer.
5. If the buffer is full the producer goes to sleep.
6. If the buffer is empty then consumer goes to sleep.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
Output
1. Producer
2.Consumer
3.Exit
Enter your choice:1
Result
Thus the Producer consumer problem has been Simulated successfully.
Exp. No. 5b Dining-Philosophers problem
Date:
AIM: To Write a C program to simulate the concept of Dining-Philosophers problem.
DESCRIPTION
The dining-philosophers problem is considered a classic synchronization problem
because it is an example of a large class of concurrency-control problems. It is a simple
representation of the need to allocate several resources among several processes in a
deadlock-free and starvation-free manner. Consider five philosopherswho spend their lives
thinking and eating. The philosophers share a circular table surrounded by five chairs, each
belonging to one philosopher. In the center of the table is a bowl of rice, and the table is
laid with five single chopsticks. When a philosopher thinks, she does not interact with her
colleagues. From time to time, a philosopher gets hungry and tries to pick up the two
chopsticks that are closest to her (the chopsticks that arebetween her and her left and right
neighbors). A philosopher may pick up only one chopstick at a time. Obviously, she
cam1ot pick up a chopstick that is already in the hand of a neighbor. When a hungry
philosopher has both her chopsticks at the same time, she eats without releasing her
chopsticks. When she is finished eating, she puts down both of her chopsticks and starts
thinking again. The dining-philosophers problem may lead to a deadlock situation and
hence some rules have to be framed to avoid the occurrence of deadlock.
Algorithm:
1. The philosopher is instructed to think till the left fork is available, when it is available,
hold it.
2. The philosopher is instructed to think till the right fork is available, when it is available,
hold it.
3. The philosopher is instructed to eat when both forks are available.
4. then, put the right fork down first
5. then, put the left fork down next
6. repeat from the beginning.
PROGRAM
int tph, philname[20], status[20], howhung, hu[20], cho;
main()
{
int i; clrscr();
printf("\n\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total no.
of philosophers: ");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i]=(i+1); status[i]=1;
}
printf("How
many are
hungry : ");
scanf("%d",
&howhung);
if(howhung==t
ph)
{
printf(“\n All are hungry..\nDead lock
stage will occur”);
printf(\n”Exiting\n”);
else{
for(i=0
;i<how
hung;i
++){
printf(“Enterphilosopher%dposition:”,(i+1));
scanf(“%d”,&hu[i]);
status[hu[i]]=2;
}
do
{
printf("1.One can eat at a time\t2.Two can eat at a time
\t3.Exit\nEnter your choice:");
scanf("%d", &cho);
switch(cho)
{
case 1: one();
break;
case 2: two();
break;
case 3: exit(0);
default: printf("\nInvalid option..");
}
}while(1);
}
}
one()
{
int pos=0, x, i;
printf("\nAllow one philosopher to eat at any time\n");
or(i=0;i<howhung; i++, pos++)
{
printf("\nP %d is granted to eat", philname[hu[pos]]);
for(x=pos;x<howhung;x++)
printf("\nP %d is waiting", philname[hu[x]]);
}
}
two()
{
int i, j, s=0, t, r, x;
printf("\n Allow two philosophers to eat at same
time\n"); for(i=0;i<howhung;i++)
{
for(j=i+1;j<howhung;j++)
{
if(abs(hu[i]-hu[j])>=1&& abs(hu[i]-hu[j])!=4)
{
printf("\n\ncombination %d \n",
(s+1));t=hu[i];
r=hu[j]; s++;
printf("\nP %d and P %d are granted to eat",
philname[hu[i]],philname[hu[j]]);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}
}
}
INPUT
DINING PHILOSOPHER PROBLEM
Enter the total no. of philosophers: 5 How many are hungry : 3
Enter philosopher 1 position: 2
Enter philosopher 2 position: 4
Enter philosopher 3 position: 5
OUTPUT
1. One can eat at a time 2.Two can eat at a time 3.Exit Enter your choice: 1
combination 3
P 5 and P 0 are granted to eat P 3 is waiting
1. One can eat at a time 2.Two can eat at a time 3.Exit Enter your choice: 3
Result
Thus the Dining Philosopher problem has been implemented successfully.
Exp. No. 6 Bankers Algorithm
Date:
Aim
To avoid deadlocks to a resource allocation system with multiple instances using bankers algorithm.
Banker’s Algorithm
Data structures maintained are:
Available—vector of available resources o Max—matrix contains demand of each process
Allocation—matrix contains resources allocated to each process o Need—matrix contains remaining resource
need of each process
Safety algorithm is used to determine whether system is in a safe state
Resource request algorithm determines whether requests can be safetly granted
Algorithm
1. Read number of resources
2. Read max. instances of each resource type
3. Read number of process
4. Read allocation matrix for each process
5. Read max matrix for each process
6. Display available resources
7. Display need matrix using formula Need = Max - Allocation
8. Determine the order of process to be executed for a safe state
9. Stop
Program
/* Banker algorithm for deadlock avoidance - bankersalgo.c */
#include <stdio.h>
#include <conio.h>
main() {
int output[10], ins[5], avail[5], allocated[10][5];
int need[10][5], max[10][5], p[10];
int k=0, d=0, t=0, i, pno, j, nor, count=0;
printf("Enter number of resources : ");
scanf("%d", &nor);
printf("\nEnter max instances of each resources\n");
for (i=0; i<nor; i++)
{
avail[i]=0;
printf("%c = ",(i+65));
scanf("%d", &ins[i]);
}
printf("\nEnter the No. of processes : ");
scanf("%d", &pno);
printf("\nEnter Allocation matrix \n ");
for(i=0; i<nor; i++)
printf("\t%c", (i+65)); printf("\n");
for(i=0; i<pno; i++)
{
p[i]=i;
printf("P%d\t", p[i]);
for (j=0; j<nor; j++)
{
scanf("%d", &allocated[i][j]);
avail[j] += allocated[i][j];
}
}
printf("\nEnter Max matrix \n ");
for(i=0; i<nor; i++)
{
printf("\t%c", (i+65));
avail[i] = ins[i] - avail[i];
}
printf("\n");
for (i=0; i<pno; i++)
{
printf("P%d\t",i);
for (j=0; j<nor; j++)
scanf("%d", &max[i][j]); }
printf("\n");
printf("Available resources are : \n");
for(i=0; i<nor; i++)
printf("%c = %d \n", (i+65), avail[i]);
printf("\nNeed matrix is :\n"); for(i=0; i<nor; i++)
printf("\t%c", (i+65)); printf("\n");
for (i=0; i<pno; i++) {
printf("P%d\t",i);
for (j=0; j<nor; j++)
printf("%d\t", max[i][j]-allocated[i][j]); printf("\n");
}
A:
d = -1;
for (i=0;i <pno; i++)
{
count = 0; t = p[i];
for (j=0; j<nor; j++)
{
need[t][j] = max[t][j] - allocated[t][j];
if(need[t][j] <= avail[j]) count++;
}
if(count == nor)
{
output[k++] = p[i];
for (j=0; j<nor; j++)
avail[j] += allocated[t][j]; }
else
p[++d] = p[i]; }
if(d != -1)
{
pno = d + 1; goto A; }
printf("\n Process Execution Order : ");
printf("<");
for (i=0; i<k; i++)
printf(" P%d ", output[i]); printf(">");
}
Output
Enter number of resources : 3
Enter max instances of each resources
= 10
=5
=7
Enter the No. of processes : 5
Enter Allocation matrix
A B C
P0 0 1 0
P1 2 0 0
P2 3 0 2
P3 2 1 1
P4 0 0 2
Enter Max matrix
A B C
P0 7 5 3
P1 3 2 2
P2 9 0 2
P3 2 2 2
P4 4 3 3
Available resources are :
=3
=3
=2
Need matrix is :
A B C
P0 7 4 3
P1 1 2 2
P2 6 0 0
P3 0 1 1
P4 4 3 1
Process Execution Order : < P1 P3 P4 P0 P2 >
Result
Thus deadlock is avoided for multiple instances of resources using bankers algorithm.
Exp. No. 7a Contiguous Allocation
Date:
Aim
To implement file allocation on free disk space in a contiguous manner.
File Allocation
The three methods of allocating disk space are:
Contiguous allocation
Linked allocation
Indexed allocation
Contiguous
Each file occupies a set of contiguous block on the disk.
The number of disk seeks required is minimal.
The directory contains address of starting block and number of contiguous block (length) occupied.
Supports both sequential and direct access.
First / best fit is commonly used for selecting a hole.
Algorithm
1. Assume no. of blocks in the disk as 20 and all are free.
2. Display the status of disk blocks before allocation.
3. For each file to be allocated:
4. Get the filename, start address and file length
5. If start + length > 20, then goto step 2.
6. C heck to see whether any block in the range (start, start + length-1) isallocated. If so, then go to step 2.
7. Allocate blocks to the file contiguously from start block to start + length – 1.
8. Display directory entries.
9. Display status of disk blocks after allocation
10. Stop
Program
/* Contiguous Allocation - cntalloc.c */
#include <stdio.h>
#include <string.h>
int num=0, length[10], start[10];
char fid[20][4], a[20][4];
void directory()
{
int i;
printf("\nFile Start Length\n");
for(i=0; i<num; i++)
printf("%-4s %3d %6d\n",fid[i],start[i],length[i]);
}
void display()
{
int i;
for(i=0; i<20; i++)
printf("%4d",i);
printf("\n");
for(i=0; i<20; i++)
printf("%4s", a[i]);
}
main() {
int i,n,k,temp,st,nb,ch,flag; char id[4];
for(i=0; i<20; i++) strcpy(a[i], "");
printf("Disk space before allocation:\n");
display();
do
{
printf("\nEnter File name (max 3 char) : ");
scanf("%s", id);
printf("Enter start block : ");
scanf("%d", &st);
printf("Enter no. of blocks : ");
scanf("%d", &nb);
strcpy(fid[num], id); length[num] = nb; flag = 0;
if((st+nb) > 20)
{
printf("Requirement exceeds range\n"); continue;
}
for(i=st; i<(st+nb); i++)
if(strcmp(a[i], "") != 0) flag = 1;
if(flag == 1)
{
printf("Contiguous allocation not possible.\n"); continue;
}
start[num] = st; for(i=st; i<(st+nb); i++) strcpy(a[i], id);;
printf("Allocation done\n");
num++;
printf("\nAny more allocation (1. yes / 2. no)? : ");
scanf("%d", &ch); } while (ch == 1);
printf("\n\t\t\tContiguous Allocation\n");
printf("Directory:"); directory();
printf("\nDisk space after allocation:\n");
display();
printf("\n");
}
Output
Disk space before allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Enter File name (max 3 char) : ls
Enter start block : 3
Enter no. of blocks : 4
Allocation done
Any more allocation (1. yes / 2. no)? : 1
Enter File name (max 3 char) : cp
Enter start block : 14
Enter no. of blocks : 3
Allocation done
Any more allocation (1. yes / 2. no)? : 1
Enter File name (max 3 char) : tr
Enter start block : 18
Enter no. of blocks : 3
Requirement exceeds range
Enter File name (max 3 char) : tr
Enter start block : 10
Enter no. of blocks : 3
Allocation done
Any more allocation (1. yes / 2. no)? : 1
Enter File name (max 3 char) : mv
Enter start block : 0
Enter no. of blocks : 2
Allocation done
Any more allocation (1. yes / 2. no)? : 1
Enter File name (max 3 char) : ps
Enter start block : 12
Enter no. of blocks : 3
Contiguous allocation not possible.
Any more allocation (1. yes / 2. no)? : 2
Contiguous Allocation Directory:
File Start Length
ls 3 4
cp 14 3
tr 10 3
mv 0 2
Disk space after allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
mv mv ls ls ls ls tr tr tr cp cp cp
Result
Thus contiguous allocation is done for files with the available free blocks.
Exp. No. 7b. Linked Allocation
Date:
Aim
To implement file allocation on free disk space as a linked list of disk blocks.
Linked
Each file is a linked list of disk blocks.
The directory contains a pointer to first and last blocks of the file.
The first block contains a pointer to the second one, second to third and so on.
File size need not be known in advance, as in contiguous allocation.
No external fragmentation.
Supports sequential access only.
Indexed
In indexed allocation, all pointers are put in a single block known as index block.
The directory contains address of the index block.
The ith entry in the index block points to ith block of the file.
Indexed allocation supports direct access.
It suffers from pointer overhead, i.e wastage of space in storing pointers.
Algorithm
1. Define file table as a linked list structure
2. Get number of files to be stored.
3. For each file:
4. Obtain number of disk blocks
5. Obtain randomly allocated disk blocks
6. Create a single linked list of nodes for the specified blocks.
7. Get the filename to be searched.
8. List disk blocks of that file as a linked list
9. Stop
Program
/* Linked list file allocation */
#include <stdio.h>
struct filetable
{ char name[20];
int nob;
struct block *sb; }
ft[30];
struct block
{ int bno;
struct block *next;
};
main() {
int i, j, n;
char str[20];
struct block *temp;
printf("Enter no. of files: ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("\nEnter file name %d : ",i+1);
scanf("%s", ft[i].name);
printf("Enter no of blocks in file %d : ", i+1);
scanf("%d", &ft[i].nob);
ft[i].sb = (struct block*)malloc(sizeof(struct block));
temp = ft[i].sb;
printf("Enter the disk blocks : ");
scanf("%d", &temp->bno); temp->next = NULL;
for(j=1; j<ft[i].nob; j++)
{
temp->next = (struct block*)malloc(sizeof(struct block));
temp = temp->next;
scanf("%d", &temp->bno);
}
temp->next = NULL;
}
printf("\nEnter file name to be searched : ");
scanf("%s", str); for(i=0; i<n; i++)
if(strcmp(str, ft[i].name)==0)
break;
if(i == n)
printf("\nFile Not Found");
else
{
printf("\nFilename No. of Blocks Blocks Occupied");
printf("\n % s\t\t%d\t", ft[i].name, ft[i].nob);
temp = ft[i].sb;
for(j=0; j<ft[i].nob; j++)
{
printf("%d -> ", temp->bno);
temp = temp->next;
}
printf("NULL");
}
}
Output
Enter no. of files: 3
Enter file name 1 : hello.c
Enter no. of blocks in file 1 : 3
Enter the disk blocks : 12 23 34
Enter file name 2 : first.cpp
Enter no. of blocks in file 2 : 3
Enter the disk blocks : 22 33 44
Enter file name 3 : profile.doc
Enter no. of blocks in file 3 : 3
Enter the disk blocks : 87 76 65
Enter file name to be searched : first.cpp
Filename No. of Blocks Blocks Occupied
first.cpp 3 22 -> 33 -> 44 -> NULL
Result
Thus linked list allocation is done for files with the available free blocks.
Exp. No. 7c Memory Management With Fixed Partitioning Technique (MFT)
Date:
AIM:
DESCRIPTION:
In this the memory is divided in two parts and process is fit into it. The process which is best
suited will be placed in the particular memory where it suits. In MFT, the memory is partitioned
into fixed size partitions and each job is assigned to a partition. The memory assigned to a
partition does not change. In MVT, each job gets just the amount of memory it needs. That is, the
partitioning of memory is dynamic and changes as jobs enter and leave the system. MVT is a more
``efficient'' user of resources. MFT suffers with the problem of internal fragmentation and MVT
suffers with external fragmentation.
ALGORITHM:
1. Declare variables.
2. Enter total memory size ms.
3. Allocate memory for os.Ms=ms-os
4. Read the no partition to be divided n Partition size=ms/n.
5. Read the process no and process size.
6. If process size is less than partition size allot else blocke the process.
While allocating update memory wastage-external fragmentation.
if(pn[i]==pn[j])f=1;
if(f==0){ if(ps[i]<=siz)
{
extft=extft+size- ps[i];avail[i]=1; count++;
}
}
7. Print the results
SOURCE CODE :
#include<stdio.h>
#include<conio.h>
main()
{
int ms, bs, nob, ef,n,
mp[10],tif=0; int i,p=0;
clrscr();
printf("Enter the total memory available (in Bytes) -- ");
scanf("%d",&ms);
printf("Enter the block size (in Bytes) -- ");
scanf("%d", &bs);
nob=ms/bs;
ef=ms - nob*bs;
printf("\nEnter the number of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter memory required for process %d (in Bytes)-- ",i+1);
scanf("%d",&mp[i]);
}
printf("\nNo. of Blocks available in memory--%d",nob);
printf("\n\nPROCESS\tMEMORYREQUIRED\tALLOCATED\tINTERNAL
FRAGMENTATION");
for(i=0;i<n && p<nob;i++)
{
printf("\n %d\t\t%d",i+1,mp[i]);
if(mp[i] > bs)
printf("\t\tNO\t\t---");
else
{
printf("\t\tYES\t%d",bs-mp[i]);
tif = tif + bs-mp[i];
p++;
}
}
if(i<n)
printf("\nMemory is Full, Remaining Processes cannot be accomodated");
printf("\n\nTotal Internal Fragmentation is %d",tif);
printf("\nTotal External Fragmentation is %d",ef);
getch();
}
INPUT
Enter the total memory available (in Bytes) -- 1000
Enter the block size (in Bytes) ------ 300
Enter the number of processes – 5
Enter memory required for process 1 (in Bytes) -- 275
Enter memory required for process 2 (in Bytes) -- 400
Enter memory required for process 3 (in Bytes) -- 290
Enter memory required for process 4 (in Bytes) -- 293
Enter memory required for process 5 (in Bytes) -- 100
No. of Blocks available in memory -- 3
OUTPUT
PROCESS ALLOCAT INTERNAL
MEMORY REQUIRED ED FRAGMENTATION
1 275 YES 25
2 400 NO -----
3 290 YES 10
4 293 YES 7
Memory is Full, Remaining Processes cannot be accommodated Total
Internal Fragmentation is 42
Total External Fragmentation is 100
Result:
AIM:
To write a program to simulate the MVT algorithm
ALGORITHM:
1. Declare variables.
2. Enter total memory size ms.
3. Allocate memory for os.
Ms=ms-os
4. Read the no partition to be divided n Partition size=ms/n.
5. Read the process no and process size.
6. If process size is less than partition size allot else block the process.
While allocating update memory wastage-external fragmentation.
if(pn[i]==pn[j]) f=1; if(f==0){ if(ps[i]<=size)
{
extft=extft+size- ps[i];avail[i]=1; count++;
}
}
7. Print the results
8. Stop the process.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
main()
{
int ms,mp[10],i, temp,n=0; char ch = 'y';
clrscr();
printf("\nEnter the total memory available (in Bytes)-- ");
scanf("%d",&ms);
temp=ms; for(i=0;ch=='y';i++,n++)
{
printf("\nEnter memory required for process %d (in Bytes) -- ",i+1);
scanf("%d",&mp[i]);
if(mp[i]<=temp)
{
printf("\nMemory is allocated for Process %d ",i+1);
temp = temp - mp[i];
}
else
{
printf("\nMemory is Full");
break;
}
printf("\nDo you want to continue(y/n) -- ");
scanf(" %c", &ch);
}
printf("\n\nTotal Memory Available -- %d", ms);
printf("\n\n\tPROCESS\t\t MEMORY ALLOCATED "); for(i=0;i<n;i++)
printf("\n \t%d\t\t%d",i+1,mp[i]);
printf("\n\nTotal Memory Allocated is %d",ms-temp);
printf("\nTotal External Fragmentation is %d",temp);
getch();
}
OUTPUT:
Memory is Full
Result:
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf; k++)
if(frame[k] == rs[i])
avail = 1;
if(avail == 0)
{
frame[j] = rs[i];
j = (j+1) % nf;
count++;
for(k=0; k<nf; k++)
printf("%4d", frame[k]);
}
}
printf("\n\nTotal no. of page faults : %d\n",count);
}
Output
Enter length of ref. string : 20
Enter reference string :
12342156212376321236
Enter number of frames : 5
Ref. str Page frames
1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
2
1
5 1 2 3 4 5
6 6 2 3 4 5
2
1 6 1 3 4 5
2 6 1 2 4 5
3 6 1 2 3 5
7 6 1 2 3 7
6
3
2
1
2
3
6
Total no. of page faults : 10
Result
Thus page replacement was implemented using FIFO algorithm.
Exp. No. 8b LRU Page Replacement
Date:
Aim
To implement demand paging for a reference string using LRU method.
LRU
Pages used in the recent past are used as an approximation of future usage.
The page that has not been used for a longer period of time is replaced.
LRU is efficient but not optimal.
Implementation of LRU requires hardware support, such as counters/stack.
Algorithm
1 Get length of the reference string, say len.
2 Get reference string and store it in an array, say rs.
3 Get number of frames, say nf.
4 Create access array to store counter that indicates a measure of recent usage.
5 Create a function arrmin that returns position of minimum of the given array.
6 Initalize frame array upto length nf to -1.
7 Initialize position of the page replacement, say j to 0.
8 Initialize freq to 0 to track page frequency
9 Initialize no. of page faults, say count to 0.
10 For each page in reference string in the given order, examine:
a. Check whether page exist in the frame array.
i. If page exist in memory then
Store incremented freq for that page position in access array.
ii. If page does not exist in memory then
Check for any empty frames.
If there is an empty frame,
a. Assign that frame to the page
b. Store incremented freq for that page position in access array.
c. Increment count.
iii. If there is no free frame then
Determine page to be replaced using arrmin function.
Store incremented freq for that page position in access array.
Increment count.
iv. Display pages in frame array.
11 Print count.
12 Stop
Program
/* LRU page replacement - lrupr.c */
#include <stdio.h> int arrmin(int[], int);
main()
{
int i,j,len,rs[50],frame[10],nf,k,avail,count=0;
int access[10], freq=0, dm;
printf("Length of Reference string : ");
scanf("%d", &len);
printf("Enter reference string :\n");
for(i=1; i<=len; i++)
scanf("%d", &rs[i]);
printf("Enter no. of frames : ");
scanf("%d", &nf);
for(i=0; i<nf; i++)
frame[i] = -1; j = 0;
printf("\nRef. str Page frames");
for(i=1; i<=len; i++)
{
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf; k++)
{
if(frame[k] == rs[i])
{
avail = 1;
access[k] = ++freq;
break;
}
}
if(avail == 0)
{
dm = 0;
for(k=0; k<nf; k++)
{
if(frame[k] == -1)
dm = 1;
break;
}
if(dm == 1)
{
frame[k] = rs[i];
access[k] = ++freq;
count++;
}
else
{
j = arrmin(access, nf);
frame[j] = rs[i];
access[j] = ++freq;
count++;
}
for(k=0; k<nf; k++)
printf("%4d", frame[k]);
}
}
printf("\n\nTotal no. of page faults : %d\n", count);
}
int arrmin(int a[], int n)
{
int i, min = a[0];
for(i=1; i<n; i++)
if (min > a[i])
min = a[i];
for(i=0; i<n; i++)
if (min == a[i])
return i;
}
Output
Length of Reference string : 20
Enter reference string :
12342156212376321236
Enter no. of frames : 5
Ref. str Page frames
1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
2
1
5 1 2 3 4 5
6 1 2 6 4 5
2
1
2
3 1 2 6 3 5
7 1 2 6 3 7
6
3
2
1
2
3
6
Total no. of page faults : 8
Result
Thus page replacement was implemented using LRU algorithm.
Exp. No. 8c Optimal Page Replacement
Date:
Aim
To implement demand paging for a reference string using Optimal method.
Optimal
Optimal page replacement has the lowest page fault rate of all algorithms.
It does not suffer from Belady's anomaly.
The page replaced is the one that will not be used for the longest period of time.
It is difficult to implement, because it requires future knowledge of reference string.
Algorithm
1. Get number of pages.
2. Get number of frames
3. Get the reference string
4. Initialize the frame array
5. Display header
6. Create access array to store counter that indicates a measure of usage.
7. Initialize no. of page faults, say count to 0.
8. For each page in reference string in the given order, examine:
a. Check whether page exist in the frame array.
i. If page exist in memory then
1. Store incremented freq for that page position in access array.
ii. If page does not exist in memory then
b. Check for any empty frames.
i. If there is an empty frame,
1. Assign that frame to the page
2. Store incremented freq for that page position in access array.
3. Increment count.
ii. If there is no free frame then
1. Replace page using optimal algorithm.
2. Store incremented freq for that page position in access array.
3. Increment count.
9. Display pages in frame array.
10. Print count.
11. Stop
Program
/* Optimal Page Replacement - optimalpr.c */
#include <stdio.h>
int n, page[20], f, fr[20], i, pf=0, flag=0;
void display(int k, int flg)
{
printf("\nPage %d\t\t",k);
for(i=0; i<f; i++)
if(flg == 1)
printf("%d\t", fr[i]);
}
void optimal() {
int j, max, lp[10], index, m;
for(j=0; j<f; j++)
{
fr[j] = page[j];
flag = 1;
pf++;
display(page[j], flag);
}
for(j=f; j<n; j++)
{
flag = 1;
for(i=0; i<f; i++)
if(fr[i] == page[j])
flag = 0;
if(flag == 1)
{
for(i=0; i<f; i++)
lp[i] = 0;
for(i=0; i<f; i++)
{
for(m=j+1; m<n; m++)
{
if(fr[i] == page[m])
{
lp[i] = m - j;
break;
}
}
}
max = lp[0];
index = 0;
for(i=0; i<f; i++)
{
if(lp[i] == 0)
{
index = i; break;
}
else
{
if(max < lp[i])
{
max = lp[i];
index = i;
}
}
}
fr[index] = page[j];
pf++;
display(page[j], flag);
}
else
display(page[j], flag);
}
printf("\n\nTotal No. of Page Faults : %d", pf);
}
main() {
printf("Enter No. of Pages: ");
scanf("%d", &n);
printf("\nEnter No. of Frames: ");
scanf("%d", &f);
printf("\nEnter Reference String : \n");
for(i=0; i<n; i++)
scanf("%d", &page[i]);
printf("\n\n\tOptimal Page Replacement \n");
printf("\n======================================\n"); printf("Reference\t"); for(i=0; i<f;
i++)
printf("F%d\t", i);
printf("\n======================================");
for(i=0; i<f; i++)
fr[i] = -1;
optimal();
}
Output
Enter No. of Pages: 20
Enter No. of Frames: 3
Enter Reference String :
7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Optimal Page Replacement
=====================================
Reference F0 F1 F2
=====================================
Page 7 7 -1 -1
Page 0 7 0 -1
Page 1 7 0 1
Page 2 2 0 1
Page 0
Page 3 2 0 3
Page 0
Page 4 2 4 3
Page 2
Page 3
Page 0 2 0 3
Page 3
Page 2
Page 1 2 0 1
Page 2
Page 0
Page 1
Page 7 7 0 1
Page 0
Page 1
Total No. of Page Faults : 9
Result
Thus page replacement was implemented using Optimal algorithm.
Exp. No. 9a FCFS Disk Scheduling Algorithm
Date:
AIM
To implement a disk scheduling routine using FCFS technique
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.
PROGRAM
#include<stdio.h> main()
{
int t[20], n, I, j, tohm[20], tot=0;
float avhm;
clrscr();
printf(“enter the no.of tracks”);
scanf(“%d”,&n);
printf(“enter the tracks to be traversed”);
for(i=2;i<n+2;i++)
scanf(“%d”,&t*i+); for(i=1;i<n+1;i++)
{
tohm[i]=t[i+1]-t[i];
if(tohm[i]<0) tohm[i]=tohm[i]*(-1);
}
for(i=1;i<n+1;i++)
tot+=tohm[i];
avhm=(float)tot/n;
printf(“Tracks traversed\tDifference between tracks\n”);
for(i=1;i<n+1;i++)
printf(“%d\t\t\t%d\n”,t*i+,tohm*i+);
printf("\nAverage header movements:%f",avhm);
getch();
}
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
OUTPUT
Tracks traversed Difference between tracks
55 45
58 3
60 2
70 10
18 52
90 72
150 60
160 10
184 24
Result:
Thus the Disk scheduling has been done successfully using FCFS Technique
Exp. No. 9b Scan Disk Scheduling Algorithm
Date:
Aim:
To implement a routine for disk scheduling using SCAN disk technique
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.
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>
main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
clrscr();
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;t[1]=h;
printf("enter the tracks");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<n+2;i++)
{
for(j=0;j<(n+2)-i-1;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}}}
for(i=0;i<n+2;i++)
if(t[i]==h)
j=i;k=i;
p=0;
while(t[j]!=0)
{
atr[p]=t[j]; j--;
p++;
}
atr[p]=t[j];
for(p=k+1;p<n+2;p++,k++)
atr[p]=t[k+1];
for(j=0;j<n+1;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n);
getch();}
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
OUTPUT
Tracks traversed Difference between tracks
150 50
160 10
184 24
90 94
70 20
60 10
58 2
55 3
18 37
Result:
Thus the Disk scheduling has been done successfully using Scan Disk Technique
Exp. No. 9c C-Scan Disk Scheduling Algorithm
Date:
Aim:
To implement a Disk scheduling algorithm using C-SCAN Technique.
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.
Program:
#include<stdio.h> main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
clrscr();
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;t[1]=h;
printf("enter total tracks");
scanf("%d",&tot);
t[2]=tot-1;
printf("enter the tracks");
for(i=3;i<=n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<=n+2;i++)
for(j=0;j<=(n+2)-i-1;j++)
if(t[j]>t[j+1])
{
for(i=0;i<=n+2;i++)
if(t[i]==h);
j=i;break;temp=t[j];
t[j]=t[j+1];
t[j+1]=temp
}
p=0;
while(t[j]!=tot-1)
{
atr[p]=t[j]; j++;
p++;
}
atr[p]=t[j]; p++;
i=0;
while(p!=(n+3)
&& t[i]!=t[h])
{
atr[p]=t[i]; i++;
p++;
}
for(j=0;j<n+2;j++
)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-
atr[j+1];
else
d[j]=atr[j+1]-
atr[j];
sum+=d[j];
}
printf("total
header
movements%d",su
m); printf("avg is
%f",(float)sum/n);
getch();
}
INPUT
Enter the track position : 55 58 60 70 18 90 150 160 184
Enter starting position : 100
OUTPUT
Result:
Thus the Disk scheduling has been done successfully using C-Scan Disk Technique
Exp. No. 10a Sequential File Allocation Strategies
Date:
AIM:
To write a C program for implementing sequential file allocation method
DESCRIPTION:
The most common form of file structure is the sequential file in this type of file,a fixed
format is used for records. All records (of the system) have the same length, consisting of the
same number of fixed length fields in a particular order because the length and position of
each field are known, only the values of fields need to be stored, thefield name and length for
each field are attributes of the file structure.
ALGORITHM:
#include<stdio.h>
main()
{
int f[50],i,st,j,len,c,k;
clrscr();
for(i=0;i<50;i++) f[i]=0;
X:
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++) if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1) goto X;
else exit();
getch();
}
OUTPUT:
Enter the starting block & length of file 4 10
4->1
5->1
6->1
7->1
8->1
9->1
10->1
11->1
12->1
13->1
The file is allocated to disk.
Result:
Thus the File Allocation has been done successfully using Sequential Technique
Exp. No. 10b Indexed File Allocation Strategies
Date:
AIM:
To implement allocation method using chained method
DESCRIPTION:
In the chained method file allocation table contains a field which points to starting
block of memory. From it for each bloc a pointer is kept to next successive block. Hence,
there is no external fragmentation.
ALGORITHM:
q=random(100);
{
if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
4. Print the results file no, length ,Blocks allocated.
Program:
#include<stdio.h>
int f[50],i,k,j,inde[50],n,c,count=0,p;
main()
{
clrscr();
for(i=0;i<50;i++)
f[i]=0;
x: printf("enter index block\t");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1;
printf("enter no of files on index\t");
scanf("%d",&n);
}
else
{
printf("Block already allocated\n");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i]);
for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block already allocated");
goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
printf("\n allocated");
printf("\n file indexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf(" Enter 1 to enter more files and 0 to exit\t");
scanf("%d",&c);
if(c==1)
goto x;
else
exit();
getch();
}
Result:
Thus the File Allocation has been done successfully using Indexed Technique
Exp. No. 10c Linked File Allocation Strategies
Date:
AIM:
To implement linked file allocation technique.
DESCRIPTION:
In the chained method file allocation table contains a field which points to starting
block of memory. From it for each bloc a pointer is kept to next successive block. Hence,
there is no external fragmentation
ALGORTHIM:
1. Get the number offiles.
2. Get the memory requirement of each file.
3. Allocate the required locations by selecting a location randomly q=
random(100);
c) Check whether the selected location is free .
d) If the location is free allocate and set flag=1 to the allocated locations.
While allocating next location address to attach it to previous location
for(i=0;i<n;i++)
{
for(j=0;j<s[i];j++)
{
q=random(100); if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
if(j>0)
{
}
}
p=r[i][j-1]; b[p].next=q;}
4. Print the results file no, length ,Blocks allocated.
Program:
#include<stdio.h>
main()
{
int f[50],p,i,j,k,a,st,len,n,c;
clrscr();
for(i=0;i<50;i++) f[i]=0;
printf("Enter how many blocks that are already
allocated"); scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:
printf("Enter the starting index block &
length"); scanf("%d%d",&st,&len); k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{ f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already
allocated",j);
k++;
}
}
printf("\n If u want to enter one
more file? (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto
X;
else
exit();
getch( );}
OUTPUT:
Result:
Thus the File Allocation has been done successfully using Indexed Technique