0% found this document useful (0 votes)
22 views

OS Manual

lab manual

Uploaded by

Mrs. Lingeshwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

OS Manual

lab manual

Uploaded by

Mrs. Lingeshwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

DMI ENGINEERING COLLEGE

ARALVAIMOZHI,KANYAKUMARI

COMPUTER LABORATORY RECORD


UNIVERSITY REGISTER NUMBER……………………………………

Certified that this is a bonafide record of practical work done by


Mr./Ms ............................................................................................... …of
………………………………………….………………………department in the
………….……………………………………………………………..Laboratory
during the semester ………………….year……………………and submitted
for the University practical examination conducted on ..........................in
DMI ENGINEERING COLLEGE, ARALVAIMOZHI, Kanyakumari.

Lab in-charge HOD/Principal

Internal Examiner External Examiner


INDEX

Ex. No DATE LIST OF EXPERIMENTS PAGE NO SIGNATURE

INSTALLATION OF WINDOWS
OPERATING SYSTEM
1

2(a) BASIC UNIX COMMANDS

2(b) SHELL PROGRAMMING


FORK, GETPID AND EXIT
3(a) SYSTEM CALLS
3(b) WAIT SYSTEM CALL

OPEN AND CLOSE SYSTEM


3(c) CALL

FCFS SCHEDULING
4(a)

SJF SCHEDULING
4(b)

PRIORITY SCHEDULING
4(d)
INTERPROCESS
COMMUNICATION USING
5
PIPES
SEMAPHORE
6 IMPLEMENTATION
DEADLOCK AVOIDANCE(BANKER’S
7 ALGORITHM )
DEADLOCK DETECTION
8 ALGORITHM

THREADING AND
9 SYNCHRONIZATION

10 PAGING TECHNIQUE

11(a) MEMORY ALLOCATION


METHODS –FIRST FIT
11(b) MEMORY ALLOCATION METHODS
–WORST FIT

MEMORY ALLOCATION METHODS –


11(C)
BEST FIT

12(a)
PAGE REPLACEMENT
ALGORITHMS(FIFO)

12(b) PAGE REPLACEMENT


ALGORITHMS(LRU)

12(c) PAGE REPLACEMENT


ALGORITHMS(LFU)

13(a) FILE ORGANIZATION TECHNIQUE-


SINGLE LEVEL DIRECTORY

13(b)
FILE ORGANIZATION TECHNIQUE-
TWO LEVEL DIRECTORY

14(a) FILE ALLOCATION STRATEGIES-


SEQUENTIAL

14(b) FILE ALLOCATION STRATEGIES-


LINKED

14(c) FILE ALLOCATION STRATEGIES-


INDEXED

15(a) IMPLEMENTATION OF FCFS DISK


SCHEDULING ALGORITHM

15(b) IMPLEMENTATION OF SSTF DISK


SCHEDULING ALGORITHM

15(c)
IMPLEMENTATION OF SCAN DISK
SCHEDULING ALGORITHM
IMPLEMENTATION OF C-SCAN DISK
15(d) SCHEDULING ALGORITHM
lOMoARcPSD|415 024 17

|415 024 17

EXNO: 1 INSTALLATION OF WINDOWS OPERATING SYSTEM


Date:

Aim:
To install windows operating system.

Procedure:

Step1:

Step2:

Step3:
lOMoARcPSD|415 024 17

Step4:

Step5:

Step6:

Step7:
lOMoARcPSD|415 024 17

Step 8:

Step9:

Step10:
lOMoARcPSD|415 024 17

Step 11:

Step12:

Step13:

Step14:
lOMoARcPSD|415 024 17

Step15:

Step16:

Step17:

Step18:
Step 19:

Step20:

Step21:
Step 22:

Step23:

Step24:
Step25:

Step26:

Step27:
Step28:

Result:
Thus the Installation of windows operating system is completed successfully.
Exp.No:2(a) BASIC UNIX COMMANDS
Date:

Aim:
To study and execute UNIX commands.
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
calyear Displays calendar for all months of the specified year
calmonthyear Displays calendar for the specified month of the year
Who Login details of all users such as their IP,Terminal No,Username,
whoami 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
Lpfile Allows the user to spool a job along with others in a print queue.
mancmdname Manual for the given command.Press q to exit
History To display the commands used by the users logon.
Exit Exit from a process.If shell is the only process then log sout

Directorycommands

Command Function
Pwd Path of the present working directory
mkdirdir A directory is created in the given name under the current
directory
mkdirdir1dir2 A number of sub-directories can be created under one stroke
cdsubdir 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
rmdirsubdir Removes an emptysub-directory.
Filecommands

Command Function
cat>filename To create a file with some contents.To end typing press Ctrl+d.
The>symbol means redirecting out put to a file.(<for input)
catfilename Displays the file contents.
cat>>filename Used to append contents to a file
cpsrcdes Copy files to given location.If already exists,it will be
overwritten
cp–isrcdes Warns the user prior to over writing the destination file
cp–rsrcdes Copies the entire directory,all its sub-directories and files.
mvoldnew To rename an existing file or directory.–I option canal so be used
mvf1f2f3dir To move a group of files to a directory.
mv–voldnew Display name of each file as it is moved.
Rmfile Used to delete a file or group of files.–I option canal so 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.
lsname To check whether a file or directory exists.
lsname* Short-handnotationtolistoutfilenamesofaspecificpattern.
ls–a Lists all files including hidden files(files beginning with.)
ls–xdirname To have specific listing of a directory.
ls–R Recursive listing of all files in the sub directories
ls–l Long listing showing file access rights(read/write/execute -rwx
for user/group/others -ugo).
cmpfile1file2 Used to compare two files.Displays nothing if files are identical.
Wcfile It produces a statistics of lines(l), words(w) ,and characters(c).
chmodpermfile 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
SatApr913:03:47IST2011

$date+%D
04/09/11

$date+%T
13:05:33
$date+%Y
2011

$date+%H
13

$cal081998
August1998
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 908:41
Vijai pts/0 Apr 913:00 (scl-64)
cse4001 pts/3 Apr 913: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

$mkdirfilter
$ls
filterlist.shregexprshellscripts

$cdshellscripts/loops/
$

$cd
$

$cd/
[vijai@localhost/]$

[vijai@localhost/]$cd/home/vijai/shellscripts/loops/
$cd..
[vijai@localhostshellscripts]$

$rmdirfilter
$ls
list.shregexprshellscripts

$cat>greet
hicse
wishinguthebest

$catgreet
hiece-a
wishinguthebest

$cat>>greet
bye
$catgreet
hicse
wishinguthebest bye

$ls
greetlist.shregexprshellscripts

$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

$cpgreet./regexpr/
$ls
greetlist.shregexprshellscripts
$ls./regexpr
demogreet

$cp-igreet./regexpr/
cp:overwrite'greet'?n

$mvgreetgreet.txt
$ls
greet.txtlist.shregexprshellscripts

$mvgreet.txt./regexpr/
$ls
list.shregexprshellscripts

$rm-i*.sh
rm:remove regular file'fact.sh'? y
rm:removeregularfile'prime.sh'?y
$ls
list.shregexprshellscripts

$wclist.sh
4 9 30list.sh
$wc-llist.sh
4list.sh

$cmplist.shfact.sh
list.shfact.shdiffer:byte1,line1

$ls-llist.sh
-rw-rw-r-- 1vijai vijai 30Apr413:58list.sh

$chmodug+xlist.sh

$ls-llist.sh
-rwxrwxr-- 1vijai vijai 30Apr413:58list.sh
$chmod740list.sh
$ls-llist.sh
-rwxr----- 1vijai vijai 30Apr413:58list.sh

Result
Thus the study and execution of UNIX commands has been completed successfully.
Exp.No: 2(b) SHELLPROGRAMMING
Date:
Aim :
To write simple shell scripts using shell programming fundamentals.

Shell Programming:
The activities of a shell are not restricted to command interpretation alone. The shell also
has rudimentary programming features. Shell programs are stored in a file (with extension.sh).
Shell programs run in interpretive mode. The original UNIX came with the Bourneshell (sh) and it
is universal even today.

Preliminaries:

1. Comments in shell script start with #.


2. Shell variables are loosely typed i.e. not declared. Variables in an expression or output
must be prefixed by $.
3. The read statement is shell's internal tool for making scripts interactive.
4. Output is displayed using echo statement.
5. Expressions are computed using the expr command.Arithmetic operators are + -
*/%.Metacharacters*( )should be escaped with a\.
6. The shell scripts are executed
$sh filename
A) Swapping values of two variables:

# Swapping values – swap.sh echo -n"


Enter value for A : " read a
echo -n"Enter value for B : " read b
t=$a a=$b b=$t
echo"ValuesafterSwapping"
echo"AValueis$aandBValueis$b"

Output
$shswap.sh
Enter value for A : 12 Enter value for B
: 23 Values after Swapping
AValueis23andBValueis12

B) Farenheit to Centigrade Conversion

# Degree conversion – degconv.sh echo -n "Enter

Fahrenheit : " read f


c=`expr \( $f - 32 \) \* 5 / 9` echo "Centigrade is : $c"

Output
$shdegconv.sh
Enter Fahrenheit : 213 Centigrade is :
100
C) Biggest of 3 numbers

#Biggest–big3.sh

echo -n "Give value for A B and C: " read a b c


if [ $a -gt $b -a $a -gt $c ] then
echo "A is the Biggest number" elif [ $b -gt $c ]
then
echo "B is the Biggest number" else
echo"CistheBiggestnumber"
fi

Output
$shbig3.sh
Give value for A B and C: 4 3 4 C is the Biggest
number
D) GradeDetermination

#Grade–grade.sh

echo -n "Enter the mark : " read mark


if [ $mark-gt 90 ] then
echo "S Grade" elif [ $mark -gt 80
] then
echo "A Grade" elif [ $mark -gt
70 ] then
echo "B Grade" elif [ $mark -gt
60 ] then
echo "C Grade" elif [ $mark -gt
55 ] then
echo "D Grade" elif [ $mark -ge
50 ] then
echo"EGrade" else
echo"UGrade"
fi

Output
$shgrade.sh
Enterthe mark : 65 C Grade

E) Vowel or Consonant
#Vowel-vowel.sh
echo -n "Key in a lower case character : " read choice
case$choicein
a|e|i|o|u)echo"It'saVowel";;
*)echo"It'saConsonant"
esac
Output
$shvowel.
Key in a lower case character : e It's a Vowel

F) SimpleCalculator

# Arithmetic operations — calc.sh echo -n "Enter the


two numbers : " read a b
echo " 1. Addition" echo " 2.
Subtraction"
echo " 3. Multiplication" echo " 4. Division"
echo -n "Enter the option : " read option
case$optionin
1) c=`expr $a+$b` echo"$a + $b = $c";;
2) c=`expr $a-$b` echo"$a - $b = $c";;
3) c=`expr $a \* $b` echo"$a * $b = $c";;
4) c=`expr $a/$b` echo"$a / $b = $c";;
*) echo "Invalid Option" esac
Output
$shcalc.sh
Enterthetwonumbers:24
1. Addition
2. Subtraction
3. Multiplication
4. Division
Entertheoption:1
2+4=6

G) MultiplicationTable
# Multiplication table – multable.shclear
echo -n "Which multiplication table? : " read n
for x in 1 2 3 4 5 6 7 8 9 10 do
p=`expr$x\*$n`
echo -n "$n X $x = $p" sleep 1
done

Output
$shmultable.sh
Which multiplication table?:6
6X1=6
6X2=12
.....
H) NumberReverse
I)
# To reverse a number – reverse.sh echo -n "Enter a
number : "
readn rd=0
while[ $n -gt 0 ] do
rem=`expr $n % 10` rd=`expr $rd \* 10 +
$rem` n=`expr $n / 10`
done
echo"Reversednumberis$rd"

Output
$shreverse.sh
Enter a number : 234 Reversed number is 432

J) PrimeNumber
# Prime number – prime.shecho -n "Enter the
number : " read n
i=2
m=`expr $n / 2` until [ $i-gt $m ] do
q=`expr$n %$i` if [ $q -eq 0 ]
then
echo "Not a Prime number" exit
fi
i=`expr$i +1` done
echo"Primenumber"

Output
$shprime.sh
Enter the number : 17 Prime number

Result:

Thus shell scripts were executed using different programming constructs.


Exp.No:3( a) FORK, GETPID AND EXIT SYSTEM CALLS
Date:

Aim:
To create a new child process using fork system call.

Algorithm:
1. Declare a variable x to be shared by both child and parent.
2. Create a child process using fork system call.
3. If return value is -1then
Print "Process creation un successfull" Terminate using exit
system call.
4. If return value is 0 then
Print"Child process"
Print process id of the child using getpid system call Print
value of x
Print process id of the parent using getpid system call
5. Otherwise
Print."Parent process"
Print process id of the parent using getpid system call Print
value of x
Print process id of the shell using getppid system call.
6. Stop

Program:

/* Process creation - fork.c */

#include <stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>

main()
{
pid_tpid; int x = 5;
pid=fork(); x++;
if(pid<0)
{
printf("Process creation error"); exit(-1);
}
elseif(pid==0)
{
printf("Child process:");
printf("\nProcess id is %d", getpid());
printf("\nValue of x is %d", x);
printf("\nProcessidofparentis%d\n",getppid());
}
else
{
printf("\nParent process:");
printf("\nProcess id is %d", getpid());
printf("\nValue of x is %d", x);
printf("\nProcessidofshellis%d\n",getppid());
}
}

Output:

$gccfork.c

$./a.out
Childprocess:
Process id is 19499 Value of x is 6
Processidofparentis19498

Parent process: Process id is 19498


Value of x is 6
Processid of shell is 3266

Result:
Thus a child process is created with copy of its parent's address space.
Exp.No:3(b) WAIT SYSTEM CALL
Date:
Aim:
To block a parent process until child completes using wait system call.

Algorithm:

1. Create a child process using fork system call.


2. If return value is -1then
a. Print"Process creation unsuccessfull"
3. Terminate using exit system call.
4. If return value is > 0then
a. Suspend parent process until child completes using wait system call
b. Print"Parent starts"
c. Print even numbers from 0–10
d. Print"Parent ends"
5. If return value is 0 then
6. Print"Child starts"
a. Print odd numbers from 0–10
b. Print "Child ends"

7. Stop

Program:

/* Wait for child termination - wait.c */ #include <stdio.h>

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

main()
{
inti,status; pid_tpid;

pid=fork();
if(pid<0)
{
printf("\nProcess creation failure\n"); exit(-1);
}
elseif(pid>0)
{
wait(NULL);
printf ("\nParent starts\nEvenNos: "); for (i=2;i<=10;i+=2)
printf("%3d",i);
printf("\nParentends\n");
}
elseif(pid==0)
{
printf ("Child starts\nOddNos: "); for (i=1;i<10;i+=2)
printf("%3d",i); printf ("\nChild ends\n");
}
}

Output

$gccwait.c

$ ./a.out Childstarts
Odd Nos: 1 3 5 7 9
Child ends
Parent starts
EvenNos: 2 4 6 8 10
Parentends

Result:
Thus using wait system call zombie child processes were avoided.
Exp.No:3(c) OPEN AND CLOSE SYSTEM CALL

Date:

Aim:
To create a file and to write contents.

open( ):

 Used to open an existing file for reading/writing or to create a new file.


 Returns a filede script or whose value is negative on error.
 The mandatory flagsare O_RDONLY ,O_WRONLY and O_RDWR
 Optional flags include O_APPEND, O_CREAT, O_TRUNC,etc
 The flags are O Red.
 The mode specifies permissions for the file.

Create ():

 Used to create a new file and open it for writing.


 It is replaced with open() with flags O_WRONLY |O_CREAT |O_TRUNC

Algorithm:

1. Declare a character buffer buf to store 100 bytes.


2. Get the new file name as command line argument.
3. Create a file with the given name using open system call with O_CREAT and
O_TRUNC options.
4. Check the filed e scriptor.
a) If file creation is unsuccessful,then stop.
5. Get input from the console until user types Ctrl+D
a) Read 100bytes(max.)from console and store on to buf using read system call
b) Write length of bufonto file using write system call.
6. Close the file using close system call.
7. Stop

Program:

/* File creation - fcreate.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

void main(int argc,char *argv[ ])


{
int fd,n, len; char buf[100];
if(argc!=2)
{
printf("Usage: ./a.out<filename>\n");
exit(-1);
}

fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0644);


if(fd< 0)
{
printf("File creation problem\n");
exit(-1);
}

printf("Press Ctrl+D at end in a new line:\n");


while((n = read(0, buf, sizeof(buf))) > 0)
{
len = strlen(buf);
write(fd, buf, len);
}
close(fd);
}

Output

$gccfcreate.c

$ ./a.outhello File I/O


Open systemcall is used to either open or create a file. create system call is used to create afile. It is
seldom used.
^D

Result
Thus a file has been created within put from the user.The process can be verified by using cat command
Exp.No:4(a) FCFS SCHEDULING
Date:

Aim:
To schedule snapshot of processes queued according to FCFS scheduling.

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 member spid, btime, wtime & ttime.
2. Get length of the ready queue,i.e.,number of process(say n)
3. Obtain b time for each process.
4. The wtimef or first process is 0.
5. Compute wtime and ttime fo reach 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 GANTT chart for the above scheduling
9. Display awat time and atur
10. Stop
Program:

/* FCFS Scheduling- fcfs.c */

#include <stdio.h>
structprocess
{
int pid;
int btime;
int wtime;
int ttime;
}p[10];

void 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 FCFS 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("\nP%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("\nAverageturnaroundtime:%5.2fms\n",atur);
printf("\n\nGANTTChart\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
Result:

Thus waiting time & turnaround time for processes based on FCFS scheduling was computed
and the average waiting time was determined.
Exp.No:4 (b) 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 processs with members pid, btime, wtime &ttime.
2. Get length of the ready queue, i.e., number of process (sayn)
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. Thewtimeforfirstprocessis0.
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 GANTTchart for the above scheduling
10. Display awat and atur
11. Stop
Program

/* SJF Scheduling – sjf.c */

#include <stdio.h>
struct process
{
int pid;
int btime;
int wtime;
int ttime;
}p[10],temp;
void 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 SJF 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("\nP%-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("\nAverageturnaroundtime:%5.2fms\n",atur);
printf("\n\nGANTTChart\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
Result
Thus waiting time & turnaround time for processes based on SJF scheduling was
computed and the average waiting time was determined.
Exp.No:4(c) PRIORITY SCHEDULING
Date:

Aim:
To schedule snapshot of processes queued according to Priority Scheduling.

Priority:
 Process tha 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 instarvation,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 processas:
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 GANTT chart for the above scheduling
10. Display awat and atur
11. Stop
Program:

#include <stdio.h>
struct process
{
int pid;
int btime;
int pri;
int wtime; int ttime;
}p[10],temp;

void 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-TimeW-Time\n");
for(i=0; i<38; i++)
printf("-");
for(i=0;i<n;i++)
printf("\nP%-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("\nAverageturnaroundtime:%5.2fms\n",atur);
printf("\n\nGANTTChart\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:
Result
Thus waiting time & turnaround time for processes based on Priority scheduling was computed
and the average waiting time was determined.
Exp.No:4(d) ROUND ROBIN SCHEDULING
Date:

Aim:
To schedule snapshot of processes queued according to Round Robin Scheduling.

RoundRobin:

 All processes are process done 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(sayn)


2. Obtain Bursttime 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 is0.
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 turnaround time
8. Display the GANTT chart that includes
a. Order in which the processes were processed in progression of rounds
b. Turn around time Ti for each process in progression of rounds.
9. Display the bursttime,turn around time and wait time foreach process(in orderof rounds
they were processed).
10. Display average wait time and turnaround time
11. Stop

Program:

/* Round robin scheduling- rr.c */

#include <stdio.h>
void 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:%.2fms\n",atur);
}
Output:

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: 5 INTERPROCESS COMMUNICATION USING PIPES
Date:

Aim:
To generate 25 fibonacci numbers and determine prime amongst them using pipe.

InterprocessCommunication:

 Inter-Processcommunication (IPC),is the mechanism whereby oneprocesscan


communicate with another process, i.e exchange data.
 IPCin linuxcanbe implementedusing pipe,sharedmemory,messagequeue,
semaphore, signal or sockets.

Pipe:

 Pipesareunidirectionalbytestreams whichconnect the standardoutput fromone


process into the standard input of another process.
 Apipeiscreatedusingthesystemcallpipethatreturnsapairoffiledescriptors.
 Thedescriptorpfd[0]isusedforreadingandpfd[1]isusedforwriting.
 Canbeusedonlybetweenparentandchildprocesses.

Algorithm:

1. Declare a array to store Fibonacci numbers


2. Decalre a array pfd with two elements for pipede scriptors.
3. Create pipe on pfd using pipe function call.
a. If return value is -1 then stop
4. Using fork system call, create a child process.
5. Letthechildprocessgenerate25fibonaccinumbersandstoretheminaarray.
6. Write the array on to pipe using write system call.
7. Block the parent till child completes using wait system call.
8. Store Fibonacci nos.written by child from the pipe in an array using read system call
9. Inspect each element of the Fibonacci array and check whether they are prime
a. If prime then print the Fibonacci term.
10. Stop

Program:

/* Fibonacci and Prime using pipe - fibprime.c */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
pid_tpid;
intpfd[2];
inti,j,flg,f1,f2,f3;
static unsigned int ar[25],br[25];
if(pipe(pfd)==-1)
{
printf("Error in pipe"); exit(-1);
}
pid=fork();
if(pid==0)
{
printf("Child process generates Fibonacci series\n" );
f1 = -1;
f2=1;
for(i=0;i<25;i++)
{
f3 = f1 + f2; printf("%d\t",f3); f1 =
f2;
f2 = f3; ar[i]=f3;
}
write(pfd[1],ar,25*sizeof(int));
}
Else if(pid>0)
{
wait(NULL);
read(pfd[0],br,25*sizeof(int));
printf("\nParentprintsFibonaccithatarePrime\n");

for(i=0;i<25;i++)
{
flg=0;
if (br[i] <= 1) flg = 1;
for(j=2;j<=br[i]/2;j++)
{
if(br[i]%j==0)
{
flg=1; break;
}
}
if (flg == 0) printf("%d\t", br[i]);
}
printf("\n");
}
else
{
printf("Process creation failed"); exit(-1);

}}
Output:

$gccfibprime.c

$./a.out

Result
Thus Fibonacci numbers that are prime is determined using IPC pipe.
Exp.No:6 SEMAPHORE IMPLEMENTATION
Date:

Aim:
To demonstrate the utility of semaphore in synchronization and multithreading.

Semaphore:

 The POSIX system in Linux has its own built-insemaphore library.


 To use it, include semaphore.h.
 Compile the code by linking with –lp thread -lrt.
 To lock a semaphore or wait,use the sem_wait function.
 To release or signal a semaphore,use the sem_post function.
 A semaphore is initialized by using sem_init(for processes or threads)
 To declare a semaphore,the datatype is sem_t.

Algorithm:

1. 2 threads are being created, one 2 seconds after the first one.

2. But the first thread will sleep for 4 seconds after acquiring the lock.
3. Thus the second thread will not enter immediately after it is called, it will enter 4–2
=2 secs after it is called.
4. Stop.

Program:

/* C program to demonstrate working of Semaphores */

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_tmutex;
void*thread(void*arg)
{
//waitsem_wait(&mutex);
printf("\nEntered..\n");
//critical section sleep(4);
//signal
printf("\nJustExiting...\n");
sem_post(&mutex);
}
int main()
{
sem_init(&mutex, 0, 1);
pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL);
sleep(2);
pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL);

pthread_join(t2,NULL);
sem_destroy(&mutex);
return0;
}

Output:

$gccsem.c-lpthread

$./a.out

Result:
Thus semaphore implementation has been demonstrated.
Ex.No: 7 DEAD LOCK AVOIDANCE
Date: BANKERS ALGORITHM

Aim:
To implement deadlock avoidance by using Banker’s Algorithm.

Algorithm:

1. Start the program.


2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether it possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety or not if we allow the
request.
9. Stop.

Program:

#include <stdio.h>
#include<conio.h>
void main()
{
int r[1][10],av[1][10];
int all[10][10], max[10][10], ne[10][10], w[10],safe[10];
int i=0, j=0, k=0, l=0, np=0, nr=0, count=0, cnt=0;
clrscr();
printf("enter the number of processes in a system");
scanf("%d", &np);
printf("enter the number of resources in a system");
scanf("%d",&nr);
for(i=1;i<=nr;i++)
{
printf("Enter no. of instances of resource R%d " ,i);
scanf("%d", &r[0][i]);
av[0][i]=r[0][i];
}
for(i=1; i<=np; i++)
for(j=1; j<=nr; j++)
all[i][j]=ne[i][j]=max[i][j]=w[i]=0;
printf("Enter the allocation matrix");
for(i=1; i<=np; i++)
{
for(j=1;j<=nr;j++)
{
scanf("%d",&all[i][j]);
av[0][j]=av[0][j]-all[i][j];
}
}
printf("Enter the maximum matrix");
for(i=1; i<=np; i++)
{

for(j=1;j<=nr;j++)
{

scanf("%d",&max[i][j]);
}
}

for(i=1;i<=np;i++)
{
for(j=1;j<=nr;j++)
{
ne[i][j]=max[i][j]-all[i][j];
}
}

for(i=1;i<=np;i++)
{
printf("pocessP%d", i);
for(j=1; j<=nr; j++)
{
printf("\n allocated %d\t",all[i][j]);
printf("maximum %d\t",max[i][j]);
printf("need%d\t",ne[i][j]);
}
printf("\n \n");
}
printf("\n Availability ");
for(i=1; i<=nr; i++)
printf("R%d %d\t", i, av[0][i]);
printf("\n ");
printf("\n safe sequence");
for(count=1;count<=np;count++)
{
for(i=1;i<=np;i++)
{
cnt=0;
for(j=1;j<=nr;j++)
{
if(ne[i][j] <= av[0][j] && w[i]==0)
cnt++;
}
if(cnt==nr)

{
k++;

safe[k] = i;
for(l=1; l<=nr; l++)
av[0][l] = av[0][l] + all[i][l];
printf("\n P%d ",safe[k]);
printf("\tAvailability ");
for(l=1; l<=nr; l++)
printf("R%d %d\t", l, av[0][l]);
w[i]=1;
}}
}getch();
}

Output
Result
Thus banker’s algorithm for deadlock avoidance was executed successfully.
Ex.No:8 DEADLOCK DETECTION

Date:

Aim:

To determine whether the process and their request for resources are in a deadlocked state.

Algorithm:

1. Mark each process that has a row in the Allocation matrix of all zeros.
2. Initialize a temporary vector W to equal the Available vector.
3. Find an index is such that process I is currently unmarked and the ith row of Q is less than or equal to
W.That is,Q ik …Wk,for1 …k …m.
4. If no such row is found, terminate the algorithm.
5. If such a row isfound, mark process I and add thec orresponding row of the allocation matrix to W.
Thatis, set Wk=Wk+Aik, for1…k…m.
6. Return to step 3.

Program:

#include<stdio.h>
static int mark[20];
int i,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++)
{
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]);

printf("\nEnter the allocation matrix:");for(i=0;i<np;i++)


for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];
}
}
//marking processes with zero allocation
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)
mark[i]=1;
}
// initialize W with avail
for(j=0;j<nr;j++)
w[j]=avail[j];
//mark processes with request less than or equal to W
for(i=0;i<np;i++)
{
int canbeprocessed=0;
if(mark[i]!=1)
{
for(j=0;j<nr;j++)
{
if(request[i][j]<=w[j])
canbeprocessed=1; else
{
canbeprocessed=0;break;
}
}
if(canbeprocessed)
{
mark[i]=1;

for(j=0;j<nr;j++)
w[j]+=alloc[i][j];
}
}
}
//checking for unmarked processes
int deadlock=0;
for(i=0;i<np;i++)
if(mark[i]!=1)
deadlock=1; if(deadlock)
printf("\n Deadlock detected");
else
printf("\n No Deadlock possible");
}
Output

Result:

Thus using given state of information deadlock process was determined.


Ex.No:9 THREADING AND SYNCHRONIZATION
Date:

Aim:

To demonstrate threading and synchronization using mutex.

Algorithm:

1. Create two threads


2. Let the threads share a common resource , say counter
3. Even if thread 2 is 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,thread 2 starts execution
5. Stop

Program:

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
pthread_ttid[2];
int counter;
pthread_mutex_t lock;

void *trythis(void*arg)
{
pthread_mutex_lock(&lock);

unsigned long i =0;


counter += 1;
printf("\n Job %d has started\n", counter);

for(i=0; i<(0xFFFFFFFF);i++);

printf("\n Job %d has finished\n", counter);

pthread_mutex_unlock(&lock);

return NULL;
}
int main( )
{
inti=0;
int error;
if(pthread_mutex_init(&lock,NULL)!=0)
{
printf("\n mutexinit has failed\n");
return 1;
}
while(i<2)
{
err = pthread_create(&(tid[i]), NULL, &trythis, NULL);
if (error != 0)
printf("\nThread can't be created:[%s]",strerror(error));
i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);
return0;
}

Output:

$gccfilename.c-lpthread

$./a.out
Result
Thus concurrent threads were synchronized using mutex lock.
Ex. No: 10 PAGING TECHNIQUE
Date:

Aim:

To determine physical address of a given page using page table.

Algorithm:

1. Get process size


2. Compte no.of pages available and display it
3. Get relative address
4. Determine the corresponding page
5. Display page table
6. Display the physical address
7.
Program:

#include <stdio.h>
#include <math.h>
void main( )
{
int size, m, n, pgno, pagetable[3]={5,6,7}, i, j, frameno;
double m1;
intra=0,ofs;
printf("Enter process size (in KB of max 12KB):");
scanf("%d", &size);
m1=size/4;
n = ceil(m1);
printf("Total No. of pages: %d", n);
printf("\nEnter relative address (in hexa) \n");
scanf("%d", &ra);
pgno = ra / 1000;
ofs = ra % 1000;
printf("page no=%d\n", pgno);
printf("page table");
for(i=0;i<n;i++)
printf("\n %d [%d]", i, pagetable[i]);
frameno = pagetable[pgno];
printf("\nPhysicaladdress:%d%d",frameno,ofs);

}
Output:

Result:
Thus physical address for the given logical address is determined using Paging technique.
Exp.No :11(a) FILE ALLOCATION METHODS

Date: FIRST FIT ALLOCATION

Aim:
To allocate memory requirements for processes using first fit allocation.

Memory Management:

 The first-fit, best-fit, or worst-fit strategy is used to select a free hole from the set of available
holes.

First fit:

 Allocate the first hole that is big enough.


 Searching starts from the beginning of set of holes.

Algorithm:

1. Declare structures hole and process to hold information about set of holes and
processes respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes,by examining each hole asfollows:
a. If holesize> process size then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
b. Otherwise check the next from the set of hole
7. Printthelistofprocessandtheirallocatedholesorunallocatedstatus.
8. Printthe list of holes,their actual and current availability.
9. Stop

Program:

/* First fit allocation - ffit.c */

#include<stdio.h>
int main()
{
int i,j,blockno,blocksize[10],processno,processsize[10];
printf("Enter the number of free blocks\n");
scanf("%d",&blockno);
printf("Enter the size of free blocks\n");
for(i=0;i<blockno;i++)
scanf("%d",&blocksize[i]);
printf("Enter the number of processes\n");
scanf("%d",&processno);
printf("Enter the size of processes\n");
for(i=0;i<processno;i++)
scanf("%d",&processsize[i]);
for(i=0;i<blockno;i++)
printf("size of free block %d: %d\n",i+1,blocksize[i]);
printf("\n\n");
for(i=0;i<processno;i++)
printf("size of process %d: %d\n",i+1,processsize[i]);
printf("\n");
printf("FIRST FIT MEMORY ALLOCATION\n\n");
printf("Processno\tAllocated block\tAllocated size\tFragment in that block\n");
i=0;
while(i<processno)
{
for(j=0;j<blockno;j++)
{
if(processsize[i]<=blocksize[j])
{
blocksize[j]-=processsize[i];
break;
}
}
printf("%d\t\t%d\t\t%d\t\t%d\n",i+1,j+1,processsize[i],blocksize[j]);
i++;
}
return 0;
}

Output:
Result
Thus processes were allocated memory using first fit method.
EX.No:11(b) WORST FIT ALLOCATION

Date

Aim
To write a c program for Worst Fit Memory Management Scheme
Algorithm
Step1: Input memory block with a size.

Step 2: Input process with size.


Step3: Initialize by selecting each process to find the maximum block size that can be assigned
to the current process.
Step4: If the condition does not fulfill,they leave the process.
Step5: If the condition is not fulfilled,then leave the process and check for the next process.
Step6: Stop.
Program:

#include<stdio.h>
int main()
{
int i,j,flag=0,blockno,blocksize[10],processno,processsize[10],lstsize,lstindex;
printf("Enter the number of free blocks\n");
scanf("%d",&blockno);
printf("Enter the size of free blocks\n");
for(i=0;i<blockno;i++)
scanf("%d",&blocksize[i]);
printf("Enter the number of processes\n");
scanf("%d",&processno);
printf("Enter the size of processes\n");
for(i=0;i<processno;i++)
scanf("%d",&processsize[i]);
for(i=0;i<blockno;i++)
printf("size of free block %d: %d\n",i+1,blocksize[i]);
printf("\n\n");
for(i=0;i<processno;i++)
printf("size of process %d: %d\n",i+1,processsize[i]);
printf("\n");
printf("WORST FIT MEMORY ALLOCATION\n\n");
printf("Processno\tAllocated block\tAllocated size\tFragment in that block\n");
i=0;
while(i<processno)
{
flag=0;
for(j=0;j<blockno;j++)
{
if(processsize[i]<=blocksize[j])
{
if(flag==0)
{
lstsize=blocksize[j];
lstindex=j;
flag++;
}
else if(blocksize[j]>lstsize)
{
lstsize=blocksize[j];
lstindex=j;
}
}
}
blocksize[lstindex]-=processsize[i];
printf("%d\t\t%d\t\t%d\t\t%d\n",i+1,lstindex+1,processsize[i],
blocksize[lstindex]);
i++;
}
return 0;
}

Output:
Result:
Thus the C Program for Worst Fit Memory Management Scheme was executed successfully.
Exp.No: 11(c) BEST FIT ALLOCATION

Date:

Aim:
To allocate memory requirements for processes using best fit allocation.

Bestfit:

 Allocate the smallest hole that is big enough.


 The list of free holes is kept sorted according to size in ascending order.
 This strategy produces smallest left over holes

Algorithm:

1. Declare structures hole and process to hold information about set of holes and
processes respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate process testoholes,by examining each hole as follows:
a. Sort the holes according to their sizes in ascending order
b. If holesize>processsize then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
c. Other wise check the next from these to sorted hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop

Program:
#include<stdio.h>
int main()
{
int i,j,flag=0,blockno,blocksize[10],processno,processsize[10],lstsize,lstindex;
printf("Enter the number of free blocks\n");
scanf("%d",&blockno);
printf("Enter the size of free blocks\n");
for(i=0;i<blockno;i++)
scanf("%d",&blocksize[i]);
printf("Enter the number of processes\n");
scanf("%d",&processno);
printf("Enter the size of processes\n");
for(i=0;i<processno;i++)
scanf("%d",&processsize[i]);
for(i=0;i<blockno;i++)
printf("size of free block %d: %d\n",i+1,blocksize[i]);
printf("\n\n");
for(i=0;i<processno;i++)
printf("size of process %d: %d\n",i+1,processsize[i]);
printf("\n");
printf("BEST FIT MEMORY ALLOCATION\n\n");
printf("Processno\tAllocated block\tAllocated size\tFragment in that block\n");
i=0;
while(i<processno)
{
flag=0;
for(j=0;j<blockno;j++)
{
if(processsize[i]<=blocksize[j])
{
if(flag==0)
{
lstsize=blocksize[j];
lstindex=j;
flag++;
}
else if(blocksize[j]<lstsize)
{
lstsize=blocksize[j];
lstindex=j;
}
}
}
blocksize[lstindex]-=processsize[i];
printf("%d\t\t%d\t\t%d\t\t%d\n",i+1,lstindex+1,processsize[i],
blocksize[lstindex]);
i++;
}
return 0;
}

Output
Result:

Thus processes were allocated memory using best fit method.


Exp. No: 12(a) PAGE REPLACEMENT ALGORITHMS

Date: FIFO PAGE REPLACEMENT

Aim:
To implement demand paging for a reference string using FIFO method.

FIFO:

 Page replacement is based on when the page was brought into memory.
 When a page should be replaced, the oldestone is chosen.
 Generally, implemented using a FIFO queue.
 Simple to implement,but not efficient.
 Results in more page faults.
 The page-fault may increase ,even if frame size is increased(Belady'sanomaly)

Algorithm:
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Forma queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the process

Program:
#include<stdio.h>
int main()
{
int i,j,n,page[50],frameno,frame[10],move=0,flag,count=0;
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
if(page[i]==frame[j])
{
flag=1;
printf("No replacement\n");
break;
}
}
if(flag==0)
{
frame[move]=page[i];
move=(move+1)%frameno;
count++;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}

Output
Result
Thus page replacement was implemented using FIFO algorithm.
Exp.No.12 (b) 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:

11. Start the process


12. Declare the size with respect to page length
13. Check the need of replacement from the page to memory
14. Check the need of replacement from old page to new page in memory
15. Form a queue to hold all pages
16. Insert the page require memory into the queue
17. Check for bad replacement and page fault
18. Get the number of processes to be inserted
19. Display the values
20. Stop the process

Program

/* LRU page replacement - lrupr.c */

#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1,repindex,
check[50]={0};
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
if(page[i]==frame[j])
{
flag=1;
printf("No replacement\n");
break;
}
}
if(flag==0&&count<frameno)
{
frame[move]=page[i];
move=(move+1)%frameno;
count++;
print(frameno,frame);
}
else if(flag==0)
{
count1=0;
for(j=i-1;j>=0;j--)
{
for(k=0;k<frameno;k++)
{
if(page[j]==frame[k]&&check[page[j]]==0)
{
check[page[j]]=1;
count1++;
repindex=k;
k=frameno;
}
}
if(count1==frameno)
break;
}
frame[repindex]=page[i];
count++;
print(frameno,frame);
}
for(j=0;j<50;j++)
check[j]=0;

}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}
Output:

Result:

Thus page replacement was implemented using LRU algorithm.


Ex.No: 12( C) LFU PAGE REPLACEMENT ALGORITHM

Aim:

To implement LFU page replacement technique.

Algorthim:

1. Start Program
2. Read Number Of Pages And Frames
3. 3.Read Each Page Value
4. Search For Page In The Frames
5. If Not Available Allocate Free Frame
6. If No Frames Is Free Replace The Page With The Page That Is Lastly Used
7.Print Page Number Of Page Faults
8. Stop process.

Program:

#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1[10]={0},
repindex,leastcount;
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
if(page[i]==frame[j])
{
flag=1;
count1[j]++;
printf("No replacement\n");
break;
}
}
if(flag==0&&count<frameno)
{
frame[move]=page[i];
count1[move]=1;
move=(move+1)%frameno;
count++;
print(frameno,frame);
}
else if(flag==0)
{
repindex=0;
leastcount=count1[0];
for(j=1;j<frameno;j++)
{
if(count1[j]<leastcount)
{
repindex=j;
leastcount=count1[j];
}
}

frame[repindex]=page[i];
count1[repindex]=1;
count++;
print(frameno,frame);
}
}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}

Output:
Result:

Thus page replacement was implemented using LRU algorithm.


Ex. No: 13(a) FILE ORGANIZATION TECHNIQUES
Date: SINGLE -LEVEL DIRECTORY

Aim:

To organize files in a single level directory structure, i, e., without sub-directories.

Algorithm:

1. Get name of directory for the user to store all the files
2. Display menu
3. Accept choice
4. If choice=1then
Accept file name without any collision
Store it in the directory
5. If choice=2 then
Accept file name
Remove filename from the directory array
6. If choice=3 then
Accept file name
Check for existence of file in the directory array
7. If choice=4then
List all files in the directory array
8. If choice=5 then
Stop

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int nf=0,i=0,j=0,ch;
char mdname[10],fname[10][10],name[10];
clrscr();
printf("Enter the directory name:");
scanf("%s",mdname);
printf("Enter the number of files:");
scanf("%d",&nf);
do
{
printf("Enter file name to be created:");
scanf("%s",name);
for(i=0;i<nf;i++)
{
if(!strcmp(name,fname[i]))
break;
}
if(i==nf)
{
strcpy(fname[j++],name);
nf++;
}
else
printf("There is already %s\n",name);
printf("Do you want to enter another file(yes - 1 or no - 0):");
scanf("%d",&ch);
}
while(ch==1);
printf("Directory name is:%s\n",mdname);
printf("Files names are:");
for(i=0;i<j;i++)
printf("\n%s",fname[i]);
getch();
}

Output:
Result:
Thus files were organized into a single level directory.
Ex. No:13 (b) TWO-LEVEL DIRECTORY

Date:

Aim:

To organize files as two-level directory with each user having his own user file directory (UFD).

Algorithm:

1. Display menu
2. Accept choice
3. If choice=1then
Accept directory name
Create an entry for that directory
4. If choice=2 then
Get directory name
If directory exist the naccept file name without collision else report error
5. If choice=3then
Get directory name
If directory exist then Get file name
If file exist in that directory then delete entry else report error
6. If choice=4then
Get directory name
If directory exist then Get filename
If file exist in that directory then
Display filename
else report error
7. If choice=5
Then Display files directory-wise
8. If choice=6 then
Stop

Program:
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\tEnter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}
printf("File %s not found",f);
goto jmp1;
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;
default:exit(0);
}
}
}
Output
Result:

Thus user files have been stored in the irrespective directories and retrieved easily.
Exp.No:14 (a) FILE ALLOCATION STRATEGIES
Date: CONTIGUOUS ALLOCATION

Aim:
To implement file allocation on free disk space in a contiguous manner.

File Allocation:

The three methods of allocating disk space are:


1. Contiguous allocation
2. Linked allocation
3. 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 arefree.


2. Display the status of disk blocks before allocation.
3. For each file to be allocated:
a. Get the filename,start address and file length
b. If start + length >20,then go to step2.
c. Check to see whether any block in the range (start, start + length-1) is
allocated. If so, then go to step 2.
d. Allocate blocks to the file contiguously from start block to start +length–1.
4. Display directory entries.
5. Display status of disk blocks after allocation
6. 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("\nFileStartLength\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]);
}

void 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("Allocationdone\n");
num++;

printf("\nAny more allocation (1. yes / 2. no)? : ");


scanf("%d", &ch);
} while (ch == 1);
printf("\n\t\t\tContiguousAllocation\n");
printf("Directory:");
directory();
printf("\nDisk space after allocation:\n");
display();
}

Output:
Result

Thus contiguous allocation is done for files with the available free blocks.
Ex.No.14(b) LINKED FILE ALLOCATION
Date:

Aim:
To implement file allocation on free disk space using linked file allocation method

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 soon.
 File size need not be known in advance,as in contiguousallocation.
 No external fragmentation.
 Supports sequential access only.

Algorithm:

1. Get no.of files


2. Accept file names and no.of blocks for each file
3. Obtain start block for each file
4. Check block availability before allocation
5. If block is unavailable then report error
6. Accept file name
7. Display linked file allocation blocks for that file
8. Stop

Program:

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
static int b[20], i, j, blocks[20][20];
char F[20][20], S[20], ch;
int sb[20], eb[20], x, n;
clrscr();
printf("\n Enter no. of Files ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter file %d name ::", i+1);
scanf("%s", &F[i]);
printf("\n Enter No. of blocks::", i+1);
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
{
printf("\n Enter Starting block of file%d::",i+1);
scanf("%d", &sb[i]);

printf("\nEnter blocks for file%d::\n", i+1);


for(j=0; j<b[i]-1;)
{
printf("\n Enter the %dblock ::", j+2);
scanf("%d", &x);
if(b[i]!=0)
{
blocks[i][j] =x;
j++;
}
else
printf("\nInvalidblock::");
}
}

printf("\nEnter the Filename :");


scanf("%s", &S);
for(i=0;i<n;i++)
{
if(strcmp(F[i],S)==0)
{
printf("\nFname\tBsize\tStart\tBlocks\n");
printf("\n -\n");
printf("\n%s\t%d\t%d\t", F[i], b[i], sb[i]);
printf("%d->",sb[i]);
for(j=0;j<b[i];j++)
{
if(b[i]!=0)
printf("%d->",blocks[i][j]);
}
}
}
printf("\n \n");
getch();
}
Output

Result
Thus blocks for file were allocated using linked allocation method.
Ex.No.14(c) INDEXED FILE ALLOCATION
Date:

Aim:
To implement file allocation on free disk space using Indexed file allocation method

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 over head. i.e., wastage of space in storing pointers

Algorithm:

1. Get no.of files.


2. Accept file names and no.of blocks for each file.
3. Obtain start block for each file.
4. Checks block availability before allocation.
5. If block is unavailable then report error.
6. Accept file name.
7. Display indexed file allocation blocks for that file.
8. Stop.

Program:

#include <stdio.h>
#include<conio.h>
int f[50],i,k,j,index[50],n,c,count=0,p;
int 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[index[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();
}

Output:
Result:

Thus blocks for file were allocated using indexed allocation method.
Ex No: 15(a) DISK SCHEDULING ALGORITHM

Date: IMPLEMENTATION OF FCFS DISK SCHEDULING ALGORITHM

Aim:

To write a C program for implementation of FCFS Disk Scheduling Algorithm.

Algorithm:

Step 1: Start the program.


Step 2: 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.
Step 3: Let us one by one take the tracks in default order and calculate the absolute distance of the track
from the head.
Step 4: Increment the total seek count with this distance.
Step 5: Currently serviced track position now becomes the new head position.
Step 6: Go to step 3 until all tracks in request array have not been serviced.
Step 7: Stop the program.

Program:

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

Result:

Thus a c program to implement the FCFS Disk Scheduling Algorithm was written and executed successfully.
Ex No :15(b) IMPLEMENTATION OF SSTF DISK SCHEDULING ALGORITHM

Aim:

To write a C program for implementation of SSTF (Short Seek Time First) Disk Scheduling Algorithm.

Algorithm:

Step 1: Start the program.


Step 2: Let Request array represents an array storing indexes of tracks that have been requested. ‘head’ is the
position of disk head.
Step 3: Find the positive distance of all tracks in the request array from head.
Step 4: Find a track from requested array which has not been accessed/serviced yet and has minimum distance
from head.
Step 5: Increment the total seek count with this distance.
Step 6: Currently serviced track position now becomes the new head position.
Step 7: Go to step 3 until all tracks in request array have not been serviced.
Step 8: Stop the program.

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);
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];
RQ[index]=1000;
count++;
}
printf("Total head movement is %d",TotalHeadMoment);
return 0;
}

Output:

Result:

Thus a c program to implement the SSTF Disk Scheduling Algorithm was written and executed successfully.
Ex No :15(c) IMPLEMENTATION OF SCAN DISK SCHEDULING ALGORITHM
Date:

Aim:

To write a C program for implementation of SCAN Disk Scheduling Algorithm.

Algorithm:

Step 1: Start the program.


Step 2: 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.
Step 3: Let direction represents whether the head is moving towards left or right.
Step 4: In the direction in which head is moving service all tracks one by one.
Step 5: Calculate the absolute distance of the track from the head.
Step 6: Increment the total seek count with this distance.
Step 7: Currently serviced track position now becomes the new head position.
Step 8: Go to step 4 until we reach at one of the ends of the disk.
Step 9: If we reach at the end of the disk reverse the direction and go to step 3 until all tracks in request array
have not been serviced.
Step 10: Stop the program.

Program:
#include<stdio.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;
}

#include<stdio.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;
queue[i+1]=0;
for(i=temp1+3,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n+1;j++)
{
diff=abs(queue[j+1]-queue[j]);

seek+=diff;

printf("Disk head moves from %d to %d with seek d\n",queue[j],queue[j+1],diff);


}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}

Output:
Result:

Thus a C program to implement the SCAN Disk Scheduling Algorithm was written and executed
successfully
Ex No :15(d) IMPLEMENTATION OF C-SCAN DISK SCHEDULING ALGORITHM

Aim:

To write a C program for implementation of C-SCAN Disk Scheduling Algorithm.

Algorithm:

Step 1: Start the program.


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

Program:

#include<
stdio.h>
main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p,
sum=0;printf("\nEnter the no of tracks to be
Traversed: "); scanf("%d'",&n);
printf("\nEnter the position of
head: ");scanf("%d",&h);
t[0]=0;
t[1]=h;
printf("\nEnter total
tracks: ");
scanf("%d",&tot);
t[2]=tot-1;
printf("\nEnter 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])
{
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;
break;
}
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("\nTotal header movements: %d",sum); printf("\nAvg is:
%f",(float)sum/n);
}
Output:
Result:

Thus a c program to implement the C-SCAN Disk Scheduling Algorithm was written and executed
Successfully

You might also like