Operating Systems Lab Manual (r20a0584)
Operating Systems Lab Manual (r20a0584)
Operating Systems
[R20A0584]
LAB MANUAL
VISION
To improve the quality of technical education that provides efficient softwareengineers with an
attitude to adapt challenging IT needs of local, national and international arena, through teaching
MISSION
Department intends to meet the contemporary challenges in the field of IT and is playing a vital
role in shaping the education of the 21st century by providing unique educational and research
opportunities.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
To facilitate the graduates with the ability to visualize, gather information, articulate,
analyze, solve complex problems, and make decisions. These are essential to address the
challenges of complex and computation intensive problems increasing their productivity.
To facilitate the graduates with the technical skills that prepare them for immediate
employment and pursue certification providing a deeper understanding of the technology in
advanced areas of computer science and related fields, thus encouraging to pursue higher
education and research based on their interest.
To facilitate the graduates with the soft skills that include fulfilling the mission, setting
goals, showing self-confidence by communicating effectively, having a positive attitude, get
involved in team- work, being a leader, managing their career and their life.
To facilitate the graduates with the knowledge of professional and ethical responsibilities
by paying attention to grooming, being conservative with style, following dress codes, safety
codes, and adapting themselves to technological advancements.
PROGRAM SPECIFIC OUTCOMES (PSOs)
After the completion of the course, B. Tech Information Technology, the graduates willhave the
following Program Specific Outcomes:
1. Fundamentals and critical knowledge of the Computer System:- Able to Understand the
working principles of the computer System and its components , Apply the knowledge to build,
asses, and analyze the software and hardware aspects of it .
3. Applications of Computing Domain & Research: Able to use the professional, managerial,
interdisciplinary skill set, and domain specific tools in development processes, identify the
research gaps, and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)
v
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
(DATA SCIENCE,CYBER SECURITY,INTERNET OF THINGS)
1. Students are advised to come to the laboratory at least 5 minutes before (to starting time), thosewho
come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab withthe
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,Procedure,
Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)needed in
the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer systemallotted to
you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observationnote
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which shouldbe
utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab sessions.
Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe
punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if anybody found
loitering outside the lab / class without permission during working hours willbe treated seriously and
punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly.
vi
II Year B. Tech CSE(DATA SCIENCE) ‐ I Sem L T/P/D C
- -/3/-1.5
(R20A0584) OPERATING SYSTEMS LAB
COURSE OBJECTIVES:
This course will enable students to :
1. Understand the design aspects of operating system concepts
2. Get introduced to basic Linux commands, system call interface for process management, inter-process
communication and I/O in UNIX.
3. Learn various process and CPU scheduling Algorithms
4.Get exposed to System calls
5. Learn deadlocks ,process management & Inter Process communication
LIST OF EXPERIMENTS:
WEEK 1: Practice File handling utilities, Process utilities, Disk utilities, Networking commands, Filters, Text
processing utilities and Backup utilities.
WEEK 2: Write a shell script that receives any number of file names as arguments checks if every argument
supplied is a file or directory and reports accordingly. Whenever the argument is a file it reports no of lines
present in it.
WEEK 3:Simulate the following CPU scheduling algorithms. a)FCFS b) SJF c) Round Robin
d) Priority.
WEEK 4: Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers Algorithm for Dead Lock
Prevention.
WEEK 5: a) Write a C program to simulate the concept of Dining-philosophers problem.
b)Write a C program to simulate producer-consumer problem using Semaphores
WEEK 6: a) Write a C program to implement kill(), raise() and sleep()functions.
b) Write a C program to implement alarm(), pause() and abort()functions
c) Write a program that illustrate communication between two process using unnamed pipes
WEEK 7: a) Write a program that illustrates communication between two process using named pipes or FIFO.
b) Write a C program that receives a message from message queue and display them.
WEEK 8: Write a C program that illustrates two processes communicating using Shared memory.
WEEK 9: Simulate all page replacement algorithms a) FIFO b) LRU c) OPTIMAL
WEEK 10: Write a C program that takes one or more file/directory names as command line input and reports
following information A) File Type B) Number Of Links C) Time of last Access D) Read, write and execute
permissions
WEEK 11:a) Implement in c language the following UNIX commands using system calls i) cat ii) ls iii) Scanning
Directories (Ex: opendir(),readdir(),etc.)
b) Write a C program to create child process and allow parent process to display “parent” and the child to display
“child” on the screen
WEEK 12: Write a C program to simulate disk scheduling algorithms. a) FCFS b) SCAN c) C-SCAN
COURSE OUTCOMES:
At the end of the course students will be able to
1. Use basic Linux commands and also system call interfaces for process management
2. Choose the best CPU scheduling algorithm for a given problem instance
3. Design and solve synchronization problems
4. Implement deadlocks, process management
5. Simulate various Disk Scheduling Algorithms
REFERENCE BOOKS:
1. Operating Systems – Internals and Design Principles, William Stallings, Fifth Edition–2005, Pearson
Education/PHI
2. Operating System - A Design Approach-Crowley, TMH.
3. Modern Operating Systems, Andrew S Tanenbaum, 2nd edition, Pearson/PHI
4. UNIX Programming Environment, Kernighan and Pike, PHI/Pearson Education
5. UNIX Internals: The New Frontiers, U. Vahalia, Pearson Education
COURSE OUTCOMES:
1. To provide an understanding of the design aspects of operating system concepts through simulation
2. Introduce basic Linux commands, system call interface for process management, inter process
communication and I/O in Unix.
3. Student will learn various process and CPU scheduling Algorithms through simulation programs
4. Student will have exposure to System calls and simulate them.
5. Student will learn deadlocks and process management & Inter Process communication and simulate
them
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
UGC-Autonomous Institution , Govt. of India
(Permanently Affiliated to JNTUH, Approved by AICTE-Accredited by NBA & NAAC- A-Grade; ISO 9001:2008Certified)
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
3 Simulate the following CPU scheduling algorithms. a)FCFS b) SJF c) Round Robin 9-14
d) Priority.
Simulate Bankers Algorithm for Dead Lock Avoidance 15-18
Simulate Bankers Algorithm for Dead Lock
4
Write a C program to simulate the concept of Dining 19-23
Write a C program to simulate producer
5
Write a C program to implement kill(), raise() and sleep()functions. 24-28
Write a C program to implement alarm(), pause() and abort()functions
6
Write a program that illustrate communication between two process using unnamed
pipes
Write a program that illustrates communication between two process using named 29-34
7 pipes or FIFO.
Write a C program that receives a message from message queue and display them.
Write a C program that illustrates two processes communicating using Shared 35-36
8 memory.
9 Simulate all page replacement algorithms a) FIFO b) LRU c) OPTIMAL 37-42
10 Write a C program that takes one or more file/directory names as command line input 43-44
and reports following information A) File Type B) Number Of Links C) Time of last
Access D) Read, write and execute permissions
a) Implement in c language the following UNIX commands using system calls i) cat ii) ls
iii) Scanning Directories (Ex: opendir(),readdir(),etc.) 45-48
11 b) Write a C program to create child process and allow parent process to display
“parent” and the child to display “child” on the screen
12 Write a C program to simulate disk scheduling algorithms. a) FCFS b) SCAN c) C-SCAN 49-53
WEEK 1
AIM : Practice File handling utilities, Process utilities, Disk utilities, Networking commands, Filters, Text
processing utilities and Backup utilities.
To Append data into the file: To append data into the same file use append operator >> to write into thefile,
else the file will be overwritten (i.e., all of its contents will be erased).
cat >> file1.txt
To display a file: This command displays the data in the file.cat file1.txt
The above cat command will concatenate the two files (file1.txt and file2.txt) and it will display the output in
the screen. Some times the output may not fit the monitor screen. In such situation you canprint those files in
a new file or display the file using less command.
cat file1.txt file2.txt | less
This rm command recursively removes the contents of all subdirectories of the tmp directory,prompting you
regarding the removal of each file, and then removes the tmpdirectory itself.
To remove more files at once: rm command removes file1.txt and file2.txt files at the same time.rm file1.txt
file2.txt
cd ..
This will change to the parent-directory from the current working directory/sub-directory.
cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into the directory (the
directory is not overwritten).
Copy two files:
cp file1.txt file2.txt
The above cp command copies the content of file1.txt to file2.txt
ls COMMAND:
ls command lists the files and directories under current working directory. Display root directorycontents:
ls /
lists the contents of root directory.
Display hidden files and directories:
ls -a
lists all entries including hidden files and directories.
Display inode information:
ls –i
ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for desired files.
Inode will be different for source and destination.
ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt' and 'file2.txt'will be
different.
mkdir command: Use this command to create one or more new directories.
Include one or more instances of the “<DIRECTORY” variable (separating each with a whitespace), and set
each to the complete path to the new directory to be created.
rmdir command:
mv command:
diff command:
comm command:
wc command:
2
PROCESS UTILITIES:
ps Command:
ps command is used to report the process status. ps is the short name for Process Status.
1. ps: List the current running processes.
Output:
PID TTY TIME CMD
2540 pts/1 00:00:00 bash
2. ps –f : Displays full information about currently running processes.
Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
3. kill COMMAND: kill command is used to kill the background process.
Step by Step process:
• Open a process music player or any file.xmms
press ctrl+z to stop the process.
• To know group id or job id of the background task.jobs -l
It will list the background jobs with its job id as,
• xmms 3956
• kmail 3467
To kill a job or process.
• kill 3956
kill command kills or terminates the background process xmms.
Disk utilities:
du (abbreviated from disk usage) is a standard Unix program used to estimate file spaceusage—space used
under a particular directory or files on a file system.
$du kt.txt pt.txt /* the first column displayed the file's disk usage */
8 kt.txt
4 pt.txt
Using -h option: As mentioned above, -h option is used to produce the output in humanreadable format.
$du -h kt.txt pt.txt
8.0K kt.txt4.0K pt.txt
/*now the output is in human readable format i.e in Kilobytes */
Using -a option
$du -a kartik
8 kartik/kt.txt 4 kartik/thakral.png
4 kartik/pt.txt 4 kartik/thakral
4 24 kartik
kartik/pranjal.
png
3
/*so with -a option used all the files (under directory kartik) disk usage info is displayed alongwith
the thakral sub-directory */
Connection closed.C:>
Finger:
The finger command displays information about users on a given host. The host can be either
local or remote.
Check all the logged-in users on the local machine −
$ finger
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
Check all the logged-in users on the remote machine –
$ finger @avtar.com
Login Name Tty Idle Login Time Office amrood pts/0 Jun 25 08:03 (62.61.164.115)
Get the information about a specific user available on the remote machine −
$ finger amrood@avtar.com
Ifconfig: Ifconfig is used to configure the network interfaces.
FILTERS
more COMMAND:
more command is used to display text in the terminal screen. It allows only backwardmovement.
1. more -c index.txt
Clears the screen before printing the file .
2. more -3 index.txt
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND:
head command is used to display the first ten lines of a file, and also specifies how many linesto
display.
1. head index.php
This command prints the first 10 lines of 'index.php'.
2. head -5 index.php
The head command displays the first 5 lines of 'index.php'.
3. head -c 5 index.php
The above command displays the first 5 characters of 'index.php'.
tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays last10
lines of a file.
1. tail index.php
It displays the last 10 lines of 'index.php'.
2. tail -2 index.php
It displays the last 2 lines of 'index.php'.
5
3. tail -n 5 index.php
Grep (Global Regular Expression Searching for a pattern), fgrep and egrep
$ grep ―sales director‖ emp1 emp2
BACKUP UTILITIES
Linux backup and restore can be done using backup commands tar, cpio, dump and restore.
Backup Restore using tar command
tar: tape archive is used for single or multiple files backup and restore on/from a tape or file.
$tar cvf /dev/rmt/0 *
Options: c -> create ; v -> Verbose ; f->file or archive device ; * -> all files and directories .
$tar cvf /home/backup *
Create a tar called backup in home directory, from all file and directories s in the currentdirectory.
Viewing a tar backup on a tape or file
$tar tvf /dev/rmt/0 ## view files backed up on a tape device.
$tar tvf /home/backup ## view files backed up inside the backup
Note: t option is used to see the table of content in a tar file.
Extracting tar backup from the tape
$tar xvf /home/backup ## extract / restore files in to current directory.
Note : x option is used to extract the files from tar file. Restoration will go to present directoryor
original backup path depending on relative or absolute path names used for backup.
Backup restore using cpio command
Using cpio command to backup all the files in current directory to tape.
find . -depth -print | cpio -ovcB > /dev/rmt/0
cpio expects a list of files and find command provides the list, cpio has to put these file onsome
destination and a > sign redirect these files to tape. This can be a file as well .
7
WEEK 2
AIM : Write a shell script that receives any number of file names as arguments checks if every
argument supplied is a file or directory and reports accordingly. Whenever the argument is a file it
reports no of lines present in it.
ALGORITHM:
step 1: if arguments are less than 1 print Enter at least one input file name and goto step 9
Step 2: selects list a file from list of arguments provided in command line
Step 3: check for whether it is directory if yes print is directory and goto step 9
step 4: check for whether it is a regular file if yes goto step 5 else goto step 8
Step 5: print given name is regular file
step 6: print No of lines in file
step 7: goto step
step 8: print not a file or adirectory
step 9: stop
for x in $*
do
if [ -f $x ]
then
echo " $x is a file "
echo " no of lines in the file are "
wc -l $x
elif [ -d $x ]
then
echo " $x is a directory "
else
echo " enter valid filename or directory name "
fi
done
OUTPUT
8
WEEK 3
AIM : To write a C program to simulate the following non-preemptive CPU scheduling algorithms to
find turnaround time and waiting time for the following.
a) FCFS b) SJF c) Round Robin d) Priority
DESCRIPTION
Assume all the processes arrive at the same time.
PROGRAM
NPUT
Enter the number of processes -- 3
Enter Burst Time for Process 0 -- 24
Enter Burst Time for Process 1 -- 3
Enter Burst Time for Process 2 -- 3
OUTPUT
PROCESS BURST TIME WAITING TIME RNAROUND TIME
P0 24 0 24
P1 3 24 27
P2 3 27 30
}
for(i=0;i<n;i++) 10
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i]; bt[i]=bt[k]; bt[k]=temp;
}
np=p[i];p[i]=p[k]; p[k]=temp;
wt[0]=wtavg=0;
}
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]); printf("\nAverage Waiting Time
-- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);getch();
}
INPUT
Enter the number of processes -- 4
Enter Burst Time for Process 0 -- 6
Enter Burst Time for Process 1 -- 8
Enter Burst Time for Process 2 -- 7
Enter Burst Time for Process 3 -- 3
OUTPUT
PROCESS BURST TIME WAITING TIME URNAROUND TIME
P3 3 0 3
P0 6 3 9
P2 7 9 16
P1 8 16 24
Average Waiting Time -- 7.000000
Average Turnaround Time -- 13.000000
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1); 11
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");scanf("%d",&t);
max=bu[0]; for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t; temp=temp+t;
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n); printf("\nThe Average Waiting time is -- %f
",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
getch();
}
INPUT
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 -- 3
OUTPUT
The Average Turnaround time is – 15.666667
The Average Waiting time is -- 5.666667
12
d) PRIORITY CPU SCHEDULING ALGORITHM
#include<stdio.h>main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;float wtavg, tatavg;
clrscr();
printf("Enter the number of processes --- ");scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i);scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];p[i]=p[k]; p[k]=temp;
temp=pri[i]; pri[i]=pri[k];pri[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
INPUT
Enter the number of processes --5
Enter the Burst Time & Priority of Process 0 --- 10
Enter the Burst Time & Priority of Process 1 --- 1
Enter the Burst Time & Priority of Process 2 --- 2
Enter the Burst Time & Priority of Process 3 --- 1
Enter the Burst Time & Priority of Process 4 --- 5
13
OUTPUT
PROCESS PRIORITY BURST TIME WAITING TIME TURNAROUND TIME
1 1 1 0 1
4 2 5 1 6
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is --- 8.200000 Average Turnaround Time is --- 12.000000
14
WEEK 4
AIM: To Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers Algorithm for Dead
Lock Prevention.
DESCRIPTION
In a multiprogramming environment, several processes may compete for a finite number of
resources. A processrequests resources; if the resources are not available at that time, the process
enters a waiting state. Sometimes, a waiting process is never again able to change state, because
the resources it has requested are held by other waiting processes. This situation is called a
deadlock. Deadlock avoidance is one of the techniques for handling deadlocks. This approach
requires that the operating system be given in advance additional information concerning which
resources a process will request and use during its lifetime. With this additional knowledge, it can
decide for each request whether or not the process should wait. To decide whether the current
request can be satisfied or must be delayed, the system must consider the resources currently
available, the resources currently allocated to each process, and the future requests and releases of
each process. Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system
with multiple instances of each resource type.
#include<stdio.h>
#include<conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n,r;
void input();
void show();
void cal();
int main()
{
int i,j;
printf("********** Banker's Algo ************\n");
input();
show();
cal();
getch();
return 0;
}
void input()
{
int i,j;
printf("Enter the no of Processes\t");
scanf("%d",&n);
printf("Enter the no of resources instances\t");
scanf("%d",&r);
printf("Enter the Max Matrix\n");
15
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&max[i][j]);
}
}
printf("Enter the Allocation Matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&alloc[i][j]);
}
}
printf("Enter the available Resources\n");
for(j=0;j<r;j++)
{
scanf("%d",&avail[j]);
}
}
void show()
{
int i,j;
printf("Process\t Allocation\t Max\t Available\t");
for(i=0;i<n;i++)
{
printf("\nP%d\t ",i+1);
for(j=0;j<r;j++)
{
printf("%d ",alloc[i][j]);
}
printf("\t");
for(j=0;j<r;j++)
{
printf("%d ",max[i][j]);
}
printf("\t");
if(i==0)
{
for(j=0;j<r;j++)
printf("%d ",avail[j]);
}
}
}
void cal()
{
int finish[100],temp,need[100][100],flag=1,k,c1=0;
16
int safe[100];
int i,j;
for(i=0;i<n;i++)
{
finish[i]=0;
}
//find need matrix
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}
printf("\n");
while(flag)
{
flag=0;
for(i=0;i<n;i++)
{
int c=0;
for(j=0;j<r;j++)
{
if((finish[i]==0)&&(need[i][j]<=avail[j]))
{
c++;
if(c==r)
{
for(k=0;k<r;k++)
{
avail[k]+=alloc[i][j];
finish[i]=1;
flag=1;
}
printf("P%d->",i);
if(finish[i]==1)
{
i=n;
}
}
}
}
}
}
for(i=0;i<n;i++)
{
if(finish[i]==1)
{
17
c1++;
}
else
{
printf("P%d->",i);
}
}
if(c1==n)
{
printf("\n The system is in safe state");
}
else
{
printf("\n Process are in dead lock");
printf("\n System is in unsafe state");
}
}
OUTPUT:
Enter the no of processes 5
Enter the no of resources instances 3
Enter the max matrix
753
322
902
222
433
Enter the allocation matrix
010
200
302
211
002
Enter available resources 3 2 2
P1->p3->p4->p2->p0->
The system is in safe state.
18
WEEK 5
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 philosophers who spend their lives thinking and eating. The philosophers
share a circular table surrounded by five chairs, eachbelonging 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 are between 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.
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==tph)
{
printf("\nAll are hungry..\nDead lock stage will occur");
printf("\nExiting..");
}
else
{
for(i=0;i<howhung;i++)
{
19
printf("Enter philosopher %d position: ",(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");for(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]]);
}
}
}
}
}
20
INPUT
DINING PHILOSOPHER PROBLEM
Enter the total no. of philosophers: 5How 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 time3.ExitEnter your choice: 1
combination 2
P 3 and P 0 are granted to eatP 5 is waiting
combination 3
P 5 and P 0 are granted to eatP 3 is waiting
1.One can eat at a time 2.Two can eat at a time 3.ExitEnter your choice: 3
21
AIM : b) To Write a C program to simulate producer-consumer problem using semaphores.
DESCRIPTION
Producer-consumer problem, is a common paradigm for cooperating processes. A producer
process produces information that is consumed by a consumer process. One solution to the
producer-consumer problem uses shared memory. To allow producer and consumer processes
to run concurrently, there must be available a buffer of items that can be filled by the producer
and emptied by the consumer. This buffer will reside in a region of memory that is shared by the
producer and consumer processes. A producer can produce one item while the consumer is
consuming another item. The producer and consumer must be synchronized, so that the
consumer does not try to consume an item that has not yet been produced.
PROGRAM
#include<stdio.h>void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0;in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf(“\n1. Produce \t 2. Consume \t3. Exit”);printf(“\nEnter your choice: ”);
scanf(“%d”, &choice);
}
switch(choice)
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);
else
{
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
Break;
case 2: if(in == out)
printf(“\nBuffer is Empty”);
Else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);out = (out+1)%bufsize;
}
Break;
22
} } }
OUTPUT
1. Produce 2. Consume 3. ExitEnter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. ExitEnter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. ExitEnter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. ExitEnter your choice: 3
OUTPUT
2. Produce 2. Consume 3. ExitEnter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. ExitEnter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. ExitEnter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. ExitEnter your choice: 3
23
WEEK 6
if (pid == 0)
{ /* child */
signal(SIGHUP, sighup);
signal(SIGINT, sigint);
signal(SIGQUIT, sigquit);
for (;;)
; /* loop for ever */
}
else /* parent */
{ /* pid hold id of child */
printf("\nPARENT: sending SIGHUP\n\n");
kill(pid, SIGHUP);
raise( ):
Program file name: raise.c#include <stdio.h> #include <stdlib.h> #include <signal.h>
return 0;
}
OUTPUT:
Registering the signal handlerRaising a SIGUSR1 signal Received a SIGUSR1 signal
25
AIM: Implement alarm(), pause() and abort() functions using a C program.
void timestamp()
{
time_t t;
time(&t);
printf("the time is %s", ctime(&t));
}
main()
{
struct sigaction sigact;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigact.sa_handler = catcher;
sigaction(SIGALRM, &sigact, NULL);
alarm(10);
printf("before pause... ");timestamp();
pause();
printf("after pause... ");timestamp();
}
OUTPUT:
before pause... the time is Fri Jun 16 09:42:29 2001inside catcher...
26
abort():
int main(void)
{
abort();
printf("\"abort() called prior to printf()\"\n");
return 0;
}
AIM:- To write a C program that illustrate communication between two process usingunnamed pipes
Program file name: unnamed_pipe.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
void server(int,int);
void client(int,int);
int main()
{
int p1[2],p2[2],pid;
pipe(p1);
pipe(p2);
pid=fork();
if(pid==0)
{
close(p1[1]);
close(p2[0]);
server(p1[0],p2[1]);
return 0;
}
close(p1[0]);
close(p2[1]);
client(p1[1],p2[0]);
wait();
return 0;
}
27
void client(int wfd,int rfd)
{
int i,j,n;
char fname[2000];
char buff[2000];
printf("ENTER THE FILE NAME :");
scanf("%s",fname);
printf("CLIENT SENDING THE REQUEST ......................................PLEASE WAIT\n");
sleep(10);
write(wfd,fname,2000);
n=read(rfd,buff,2000);
buff[n]='\0';
printf("THE RESULTS OF CLIENTS ARE ...................................... \n");
write(1,buff,n);
}
28
WEEK 7
AIM :a) To Write a program that illustrates communication between two process using named pipes or FIFO.
Algorithm:
Create two processes, one is fifoserver_twoway and another one is fifoclient_twoway.
Programs:
/* Filename: fifoserver_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
char readbuf[80];
char end[10];
int to_end;
int read_bytes;
29
/* Create the FIFO if it does not exist */mkfifo(FIFO_FILE, S_IFIFO|0640);
strcpy(end, "end");
fd = open(FIFO_FILE, O_RDWR);
while(1)
{
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOSERVER: Received string: \"%s\" and length is %d\n", readbuf,(int)strlen(readbuf));
to_end = strcmp(readbuf, end);
30
/* Filename: fifoclient_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
while (1)
{
printf("Enter string: ");
fgets(readbuf, sizeof(readbuf), stdin);
stringlen = strlen(readbuf);
readbuf[stringlen - 1] = '\0';
end_process = strcmp(readbuf, end_str);
31
OUTPUT:
FIFO_CLIENT: Send messages, infinitely, to end enter "end"
Enter string: LINUX IPCs
FIFOCLIENT: Sent string: "LINUX IPCs" and string length is 10
FIFOCLIENT: Received string: "sCPI XUNIL" and length is 10
Enter string: Inter Process Communication
FIFOCLIENT: Sent string: "Inter Process Communication" and string length is 27
FIFOCLIENT: Received string: "noitacinummoC ssecorP retnI" and length is 27
Enter string: end
FIFOCLIENT: Sent string: "end" and string length is 3
AIM : b) Write a C program that receives a message from message queue and display them.
ALGORITHM:
Step 1:Start
Step 2:Declare a message queue
typedef struct msgbuf
{
long mtype;
char mtext[MSGSZ];
}
message_buf;
Mtype =0 Retrieve the next message on the queue, regardless of its mtype.
PositiveGet the next message with an mtype equal to the specifiedmsgtyp.
Negative Retrieve the first message on the queue whose mtype fieldis less than or
equal to the absolute value of the msgtyp argument.
Usually mtype is set to1
mtext is the data this will be added to the queue.
Step 3:Get the message queue id for the "name" 1234, which was created by the serverkey = 1234
Step 4 : if ((msqid = msgget(key, 0666< 0) Then print error
The msgget() function shall return the message queue identifier associated with the argument key.
Step 5: Receive message from message queue by using msgrcv function
int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
#include < sys/msg.h>
(msgrcv(msqid, &rbuf, MSGSZ, 1, 0)msqid: message queue id
&sbuf: pointer to user defined structure MSGSZ: message sizeMessage type: 1
Message flag:The msgflg argument is a bit mask constructed by ORing together zero or more of the
following flags: IPC_NOWAIT or MSG_EXCEPT or MSG_NOERROR
Step 6:if msgrcv <0 return error
Step 7:otherwise print message sent is sbuf.mextStep 8:stop
Program:
//IPC_msgq_send.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
32
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
typedef struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
};
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1234;
if ((msqid = msgget(key, msgflg )) < 0) //Getthe message queue ID for the given key
die("msgget");
//Message Typesbuf.mtype = 1;
buflen = strlen(sbuf.mtext) + 1 ;
else
printf("Message Sent\n");
exit(0);
}
Program:
33
//IPC_msgq_rcv.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 128
printf("%s\n", rcvbuffer.mtext);exit(0);
}
34
WEEK 8
AIM: To write a C program that illustrates two processes communicating using Shared memory.
Algorithm:-
the shared memory identifier associated with key Theargument key is equal to IPC_PRIVATE. so that
step1.Start
step 2.Include header files required for the program are#include <sys/types.h>
#include <sys/ipc.h>#include <sys/shm.h>#include <unistd.h> #include <string.h> #include <errno.h>
step 3.Declare the variable which are required aspid_t pid
int *shared /* pointer to the shm */int shmid
step 4.Use shmget function to create shared memory#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg)
The shmget() function shall return the operating system selects the next availablekey for a newly created
shared block of memory.Size represents size of shared memory block Shmflg shared memory permissions
which are represented by octalinteger shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
print the shared memory idstep 5.if fork()==0 Then
begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared) *shared=2print *shared sleep(2)
print *shared
end
step 6.else shared = shmat(shmid, (void *) 0, 0) print the shared variable(shared) print *shared
begin sleep(1) *shared=30
printf("Parent value=%d\n", *shared);sleep(5)
shmctl(shmid, IPC_RMID, 0)
end
step 7.stop.
Sha.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
35
int main(void) {
pid_t pid;
int *shared; /* pointer to the shm */ i
nt shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
printf("Shared MemoryID=%u",shmid);
if (fork() == 0)
{/
* Child */
OUTPUT:
$cc shared_mem.c
$ ./a.out
Shared Memory ID=65537
Child pointer 3086680064
Child value=1
Shared Memory ID=65537
Parent pointer 3086680064
Parent value=1
Parent value=42
Child value=42
36
WEEK 9
AIM: To Simulate all page replacement algorithms a) FIFO b) LRU c) OPTIMAL
DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical memory
and physical memory. With this mechanism, an enormous virtual memory can be provided for
programmers on a smaller physical memory. There are many different page-replacement algorithms.
Every operating system probably has its own replacement scheme. A FIFO replacement algorithm
associates with each page the time when that page was brought into memory. When a page must be
replaced, the oldest page is chosen. If the recent past is used as an approximation of the near future,
then the page that has not been used for the longest period of time can be replaced. This approach is
the Least Recently Used (LRU) algorithm. LRU replacement associates with each page the time of that
page's last use. When a page must be replaced, LRU chooses the page that has not been used for the
longest period of time. Least frequently used (LFU) page-replacement algorithm requires that the
page with the smallest count be replaced. The reason for this selection is that an actively used page
should have a large reference count.
PROGRAM
37
for(j=0;j<f;j++)
printf("\t%d",m[j]);
if(k==f)
printf("\tPF No. %d",pf);
printf("\n");
if(count==f)
count=0;
}
printf("\n The number of Page Faults using FIFO are %d",pf);
getch();
}
INPUT
Enter the length of reference string – 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3
OUTPUT
The Page Replacement Process is –
-1 -1 PF No. 1
0 -1 PF No. 2
0 1 PF No. 3
0 1 PF No. 4
0 1
3 1 PF No. 5
3 0 PF No. 6
3 0 PF No. 7
2 0 PF No. 8
2 3 PF No. 9
2 3 PF No. 10
2 3
2 3
1 3 PF No. 11
1 2 PF No. 12
1 2
1 2
1 2 PF No. 13
0 2 PF No. 14
0 1 PF No. 15
39
-1 -1 2 Fault:
-1 -1 2 Fault:
-1 3 2 Fault:
1 3 2 Fault:
132
1 5 2 Fault:
4 5 2 Fault:
452
4 5 3 Fault:
2 5 3 Fault:
253
253
DESCRIPTION
Optimal page replacement algorithm has the lowest page-fault rate of all algorithms and will
never suffer from Belady's anomaly. The basic idea is to replace the page that will not be used
for the longest period of time. Use of this page-replacement algorithm guarantees the lowest
possible page fault rate for a fixed number of frames. Unfortunately, the optimal page-
replacement algorithm is difficult to implement, because it requires future knowledge of the
reference string.
PROGRAM
#include<stdio.h>int n;
main()
{
int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s;int count=1,pf=0,p=0;
float pfr;clrscr();
printf("Enter maximum limit of the sequence: ");scanf("%d",&max);
printf("\nEnter the sequence: ");for(i=0;i<max;i++)
scanf("%d",&seq[i]); printf("\nEnter no. of frames: ");scanf("%d",&n);
fr[0]=seq[0];pf++;
printf("%d\t",fr[0]);i=1;
while(count<n)
{
flag=1;p++;
for(j=0;j<i;j++)
{
if(seq[i]==seq[j])flag=0;
}
if(flag!=0)
{
fr[count]=seq[i]; printf("%d\t",fr[count]);count++;
pf++;
} i++;
}
40
printf("\n"); for(i=p;i<max;i++)
{
flag=1; for(j=0;j<n;j++)
{
if(seq[i]==fr[j])
flag=0;
}
if(flag!=0)
{
for(j=0;j<n;j++)
{
m=fr[j]; for(k=i;k<max;k++)
{
if(seq[k]==m)
{
pos[j]=k;break;
}
else pos[j]=1;
}
}
for(k=0;k<n;k++)
{
if(pos[k]==1)
flag=0;
}
if(flag!=0)
s=findmax(pos);if(flag==0)
{
for(k=0;k<n;k++)
{
if(pos[k]==1)
{
s=k; break;
}
}
}
fr[s]=seq[i]; for(k=0;k<n;k++)
printf("%d\t",fr[k]);
pf++; printf("\n");
}
}
pfr=(float)pf/(float)max;
printf("\nThe no. of page faults are %d",pf);printf("\nPage fault rate %f",pfr);
getch();
}
int findmax(int a[])
{
int max,i,k=0;
max=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
41
{
max=a[i];
k=i;
}
}
return k;
}
}
INPUT
Enter number of page references -- 10
Enter the reference string -- 123452525143
Enter the available no. of frames --- 3
OUTPUT
The Page Replacement Process is –
1 -1 -1 PF No. 1
1 2 -1 PF No. 2
1 2 3 PF No. 3
4 2 3 PF No. 4
5 2 3 PF No. 5
5 2 3
5 2 3
5 2 1 PF No. 6
5 2 4 PF No. 7
5 2 3 PF No. 8
42
WEEK 10
AIM: To write a C program that takes one or more file/directory names as command line input and reports
following information A) File Type B) Number Of Links C) Time of last Access D) Read, write and execute
permissions
Algorithm:
Step 1:start
Step 2:Declare struct stat a
Step 3:read arguments at command line
Step 4: set the status of the argument using stat(argv[i],&a);
Step 5:Check whether the given file is Directory file by using S_ISDIR(a.st_mode)if it is a directory file
print Directory file
Else
print is Regular fileStep6: print number of links
Step 7:print last time access
Step 8:Print Read,write and execute permissionsStep 9:stop
#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
int main(int argc,char *argv[])
{
int i,j; struct stat a;
for (i=1;i<argc;i++)
{
printf("%s : ",argv[i]);
stat(argv[i],&a);
if(S_ISDIR(a.st_mode))
{
printf("is a Directory file\n");
}
else
{
printf("is Regular file\n");
}
printf("******File Properties********\n");
printf("Inode Number:%d\n",a.st_ino);
printf("UID:%o\n",a.st_uid);
printf("GID:%o\n",a.st_gid);
printf("No of Links:%d\n",a.st_nlink);
printf("Last Access time:%s",asctime(localtime(&a.st_atime)));
43
printf("Permission flag:%o\n",a.st_mode%512);
printf("size in bytes:%d\n",a.st_size);
printf("Blocks Allocated:%d\n",a.st_blocks);
printf("Last modification time %s\n",ctime(&a.st_atime));
}
}
44
WEEK 11
AIM: a)To Implement in c language the following UNIX commands using system calls i) cat ii) ls iii) Scanning
Directories (Ex: opendir(),readdir(),etc.)
DESCRIPTION:
(i) cat COMMAND: cat linux command concatenates files and print it on the standard
output. SYNTAX:
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
-v Non-printing characters (with the exception of tabs, new-lines & form-feeds) are printed visibly.
3. To display a file:
$cat file1.txt
This command displays the data in the file.
45
In the above example the output is redirected to new file file3.txt. The cat command will create new file
file3.txt and store the concatenated output into file3.txt.
Algorithm:
Step 1:Start
Step 2:read arguments from keyboard at command line
Step 3:if no of arguments are less than two print ENTER CORRECT ARGUMENTSElse goto step 4
Step4:read the date from specified file and write it to destination fileStep 5 :stop
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
int main(int argc,char *argv[])
{
int fd,n;
char buff[512];
if(argc!=2)
printf("ENTER CORRECT ARGUMENTS :");
if((fd=open(argv[1],4))<0)
{
printf("ERROR");
return 0;
}
while(n=read(fd,buff,sizeof(buff))>0)write(1,buff,n);
}
(ii) ls
Description:
ls command is used to list the files present in a directory
Algorithm:
Step 1. Start.
Step 2. open directory using opendir( ) system call. Step 3. read the directory using readdir( ) system call.Step 4.
print dp.name and dp.inode .
Step 5. repeat above step until end of directory.Step 6: Stop.
Program name: 5b.c
#include<stdio.h> #include<dirent.h> void quit(char*,int);
int main(int argc,char **argv )
{
DIR *dirop;
struct dirent *dired;if(argc!=2)
{
printf("Invalid number of arguments\n");
46
}
if((dirop=opendir(argv[1]))==NULL) printf("Cannot open directory\n");
while((dired=readdir(dirop))!=NULL)
printf("%10d %s\n",dired>d_ino,dired>d_name);closedir(dirop);
}
#include <stdio.h>
#include <dirent.h>
int main(void)
{
struct dirent *de; // Pointer for directory entry
closedir(dr);
return 0;
OUTPUT
47
b) To write a C program to create child process and allow parent process to display “parent” and the child to
display “child” on the screen
ALGORITHM:
Step 1: start
Step2: call the fork() function to create a childprocess fork function returns 2 values
step 3: which returns 0 to child process
step 4:which returns process id to the parentprocess step 5:stop
Output:
[root@dba ~]# cc -o 8
8a.c[root@dba ~]# ./8
the child process ID is
4485 the parent process
ID is 4484
48
WEEK 12
AIM: Write a C program to simulate disk scheduling algorithms. a) FCFS b) SCAN c) C-SCAN
DESCRIPTION
One of the responsibilities of the operating system is to use the hardware efficiently. For the disk
drives, meeting this responsibility entails having fast access time and large disk bandwidth. Both the
access time and the bandwidth can be improved by managing the order in which disk I/O requests are
serviced which is called as diskscheduling. The simplest form of disk scheduling is, of course, the first-
come, first-served (FCFS) algorithm. This algorithm is intrinsically fair, but it generally does not provide
the fastest service. In the SCAN algorithm, the diskarm starts at one end, and moves towards the other
end, servicing requests as it reaches each cylinder, until it gets to the other end of the disk. At the
other end, the direction of head movement is reversed, and servicing continues. The head
continuously scans back and forth across the disk. C-SCAN is a variant of SCAN designed to provide a
more uniform wait time. Like SCAN, C-SCAN moves the head from one end of the disk to the other,
servicing requests along the way. When the head reaches the other end, however, it immediately
returns to the beginning of the disk without servicing any requests on the return trip
PROGRAM
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
OUTPUT
Tracks Difference between
traversed tracks
49
55 45
58 3
60 2
70 10
18 52
90 72
150 60
160 10
184 24
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,sum=0,n;
int d[20];
int disk; //loc of head
int temp,max;
int dloc; //loc of disk in array
clrscr();
printf("enter number of location\t");
scanf("%d",&n);
printf("enter position of head\t");
scanf("%d",&disk);
printf("enter elements of disk
queue\n");
for(i=0;i<n;i++)
{
scanf("%d",&d[i]);
}
d[n]=disk;
n=n+1;
for(i=0;i<n;i++) // sorting disk
locations
{
for(j=i;j<n;j++)
{
if(d[i]>d[j])
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}
50
}
max=d[n];
for(i=0;i<n;i++) // to find loc of disc in array
{
if(disk==d[i]) { dloc=i; break; }
}
for(i=dloc;i>=0;i--)
{
printf("%d -->",d[i]);
}
printf("0 -->");
for(i=dloc+1;i<n;i++)
{
printf("%d-->",d[i]);
}
sum=disk+max;
printf("\nmovement of total cylinders %d",sum);
getch();
return 0;
}
OUTPUT:
Enter no of location 8
Enter position of head 53
Enter elements of disk queue
98
183
37
122
14
124
65
67
53->37->14->0->65->67->98->122->124->183->
Movement of total cylinders 236.
51
C-SCAN DISK SCHEDULING ALGORITHM
#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++)
52
{
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
53