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

Os Lab Manual

Uploaded by

Yogesh 02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Os Lab Manual

Uploaded by

Yogesh 02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

CS3461

OPERATING SYSTEMS
LABORATORY

1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

RECORD NOTE BOOK


2022 – 2023

DHANALAKSHMI SRINIVASAN COLLEGE OF


ENGINEERING
NAVAKKARAI, COIMBATORE-641 105

2
LIST OF EXPERIMENTS:
1. Installation of windows operating system
2. Illustrate UNIX commands and Shell Programming
3. Process Management using System Calls : Fork, Exit, Getpid, Wait, Close
4. Write C programs to implement the various CPU Scheduling Algorithms
5. Illustrate the inter process communication strategy
6. Implement mutual exclusion by Semaphore
7. Write C programs to avoid Deadlock using Banker's Algorithm
8. Write a C program to Implement Deadlock Detection Algorithm
9. Write C program to implement Threading
10. Implement the paging Technique using C program
11. Write C programs to implement the following Memory Allocation Methods
a. First Fit
b. Worst Fit
c. Best Fit
12. Write C programs to implement the various Page Replacement Algorithms
13. Write C programs to Implement the various File Organization Techniques
14. Implement the following File Allocation Strategies using C programs
a. Sequential
b. Indexed
c. Linked
15. Write C programs for the implementation of various disk scheduling algorithm

16. Install any guest operating system like Linux using VMware

PREPARED BY
Mr.Haribaskar S/AP

3
Ex. No: 1
BASICS OF UNIX COMMANDS
Date:
AIM:

To execute various UNIX commands.

PROCEDURE TO USE PUTTY SERVER(UNIX):

Step-1: Double Click on the icon named putty located in the desktop.
Step-2: In the hostname, type the following address: 192.168.15.181[Server IP address] and port
as 22.
Step-3: Select the connection type as SSH and click open.
Step-4: Once the putty login page is opened, type the login name as IT followed by your rollno.
Eg: IT01, IT37, etc, and press enter..
Step-5: Give the same as your password and press
enter. Step-7: Start trying out the commands given
below.

ESSENTIAL UNIX COMMANDS


These are ten commands that you really need to know in order to get started with
UNIX.

Command Example Description

Lists files in current


ls
1. ls directory
ls -alF
List in long format

cd tempdir Change directory to tempdir


cd .. Move back one directory Move
2. cd
cd ~dhyatt/web- into dhyatt's web-docsdirectory
docs

Make a directory called


3. mkdir mkdir graphics
graphics

Remove directory (must be


4. rmdir rmdir emptydir
empty)

cp file1
Copy file into
5. cp web- docs
directory Make backup
cp file1 file1.bak
of file1
rm file1.bak Remove or delete
6. rm
rm *.tmp file Remove all file

mv old.html
7. mv Move or rename files
new.html

5
8. more more index.html Look at file, one page at a

5
time

9. lpr lpr index.html Send file to printer

Online manual (help) about


10. man man ls
command

VALUABLE UNIX COMMANDS


Once you have mastered the basic UNIX commands, these will be quite valuable in
managing your own account.

Command Example Description

Find which files


1. grep
grep "Hello" * contain a certain
<str><files>
word

Change file
chmod 644 permissions readonly
2. chmod <opt> *.html Change file
<file> chmod 755 permissions to
file.exe executable

3. passwd passwd Change passwd

List all running


ps aux
processes by #IDList
4. ps <opt> ps aux | grepdhyatt
process #ID'srunning
by dhyatt

5. kill <opt> Kill process with ID


kill -9 8453
<ID> #8453

Compile a
gcc file.c -o
6. gcc (g++) program written in
file g++
<source> C Compile a
fil2.cpp -o fil2
program written in
C++
gzip bigfile Compress file
7. gzip <file>
gunzip bigfile.gz Uncompress file

mail
Send file1 by
[email protected] <
8. mail (pine) email to someone
file1
Read mail using pine
pine

5
Open a connection
telnet
to vortex
9. telnet <host> vortex.tjhsst.edu
Open a secure
ssh <host> ssh -l dhyatt
connection to jazz
jazz.tjhsst.edu
as user dhyatt

10. ftp <host> ftp Upload or Download


ncftp station1.tjhsst.edu files to station1.
<host/directo ncftp Connect to archives
ry> matlab.unc.edu at UNC

FUN UNIX COMMANDS


These are ten commands that you might find interesting or amusing. They are actually quite
helpful at times, and should not be considered idle entertainment.

Command Example Description

1. who who Lists who is logged


on your machine

2. finger finger Lists who is on


computers in the lab

3. ytalk ytalk Talk online with


<user@place> dhyatt@threat dhyatt who is on
threat

4. history history Lists commands


you've done recently

5. fortune fortune Print random


humerous message

6. date date Print out current date

7. cal <mo> cal 9 2000 Print calendar for


<yr> September 2000

8. xeyes xeyes & Keep track of cursor


(in "background")

9. xcalc xcalc & Calculator


("background"
process)

5
10. mpage mpage -8 file1 Print 8 pages on a
<opt> <file> | lpr single sheet and send
to printer (the font
will be small!)

HELPFUL UNIX COMMANDS


These ten commands are very helpful, especially with graphics and word processing type
applications.

Command Example Description

1. netscape netscape & Run Netscape browser

Run graphics file


2. xv xv &
converter

3. xfig / xfig &


Run drawing program
xpaint (xpaint &)

Run photoshop type


4. gimp gimp &
program

5. ispell
ispell file1 Spell check file1
<fname>

6. latex Run LaTeX, a scientific


latex file.tex
<fname> document tool

7. xemacs / xemacs (orpico)


Different editors
pico

Run StarOffice, a full


8. soffice soffice &
word processor

9. m-tools
mdir a: DOS commands from
(mdir, mcopy,
mcopy UNIX (dir A:)
mdel,
file1 a: Copy file1 to A:
mformat, etc. )

10. gnuplot gnuplot Plot data graphically

5
USEFUL UNIX COMMANDS

These ten commands are useful for monitoring system access, or simplifying your own
environment.

Command Example Description

See how much free disk


1. df df
space

Estimate disk usage


2. du du -b subdir
of directory in Bytes

Create new command


alias lls="ls -
3. alias "lls" for long format
alF"
of ls

Permit window to
display from x-window
xhost +
program from threat
4. xhost threat.tjhsst.edu
Allow no x-window
xhost -
access from other
systems

Fold or break long lines at


fold -s
5. fold 60 characters and sendto
file1 | lpr
printer

tar -cf subdir.tar Create an archive called


subdir subdir.tar of a directory
6. tar
tar -xvf Extract files from an
subdir.tar archive file

7. ghostview(gv)
gv filename.ps View a Postscript file

ping
See if machine is
8.ping threat.tjhsst.edu
alive Print data path
(traceroute) traceroute
to a machine
www.yahoo.com

Print system usage


9. top top
and top resource hogs

10. logout How to quit a UNIX


logout or exit
(exit) shell.

RESULT:
Thus the different UNIX commands had been worked out successfully.

5
Ex. No: 2
SYSTEM CALLS OF UNIX OS
Date:

AIM:

To write a C program to implement various System Calls of UNIX operating system fork, exec,getpid,
exit, wait, close, stat, opendir, readdir

a) fork(), exec() wait() and exit():

DESCRIPTION:
Used to create new processes. The new process consistsof a copy of the address space ofthe
original process. The value of process id for the child process is zero, whereas the value of
process id for the parent is an integer value greater than zero.

ALGORITHM:
Step 1 : Declare the variable pid.
Step 2 : Get the pid value using system call fork().
Step 3 : If pid value is less than zero then print as “Fork failed”.
Step 4 : Else if pid value is equal to zero include the new process in the system‟sfile
using execlp system call.
Step 5 : Else if pid is greater than zero then it is the parent
process and it waits till the child completes using the system call wait()Step
6 : Then print “Child complete”.

PROGRAM CODING :

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void main(int argc,char *arg[])
{
int pid;
pid=fork();
if(pid<0)
{
printf("fork failed");
exit(1);
}
else if(pid==0)
{

5
execlp("whoami","ls",NULL);
exit(0);
}
else
{
printf("\n Process id is -%d\n",getpid());
wait(NULL);
exit(0);
}
}

OUTPUT:

[cse6@localhost Pgm]$ cc
prog4a.c [cse6@localhost Pgm]$
./a.out

b) getpid():

DESCRIPTION:
1. getpid( )
Each process is identified by its id value. This function is used to get the id valueof
a particular process.
2. getppid( )
Used to get particular process parent‟s id value.
3. perror( )
Indicate the process error.
ALGORITHM:
Step 1 : Declare the variables pid , parent pid , child id and grand chil id.Step 2
: Get the child id value using system call fork().
Step 3 : If child id value is less than zero then print as “error at fork()
child”. Step 4 : If child id !=0 then using getpid() system call get the
process id.
Step 5 : Print “I am parent” and print the process id.
Step 6 : Get the grand child id value using system call fork().
Step 7 : If the grand child id value is less than zero then print as “error
atfork() grand child”.
Step 8 : If the grand child id !=0 then using getpid system call get the process id.Step 9
: Assign the value of pid to my pid.
Step 10 : Print “I am child” and print the value of my pid. Step
5
11 : Get my parent pid value using system call getppid().

5
Step 12 : Print “My parent‟s process id” and its
value. Step 13 : Else print “I am the grand child”.
Step 14 : Get the grand child‟s process id using getpid() and print it as “my
processid”.
Step 15 : Get the grand child‟s parent process id using getppid() and print it as “myparent‟s
process id

PROGRAM CODING :

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main( )
{
int pid;
pid=fork( ); if(pid==-1)
{
perror(“fork failed”); exit(0);
}
if(pid==0)
{
printf(“\n Child process is under execution”);
printf(“\n Process id of the child process is %d”, getpid());
printf(“\n Process id of the parent process is %d”,
getppid());
}
else
{
printf(“\n Parent process is under execution”);
printf(“\n Process id of the parent process is %d”, getpid());
printf(“\n Process id of the child process in parent is %d”,
pid()); printf(“\n Process id of the parent of parent is %d”,
getppid());
}
return(0);
5
}

5
OUTPUT:
Child process is under execution
Process id of the child process is 9314
Process id of the parent process is 9313 Parent
process is under execution
Process id of the parent process is 9313
Process id of the child process in parent is
9314 Process id of the parent of parent is 2825

RESULT:

Thus the program was executed and verified successfully

5
Ex. No: 3
SIMULATION OF UNIX COMMANDS
Date:

AIM:

To Write a C program to simulate the operation of “ls, grep” commands in Unix.

ALGORITHM:

Step 1 : Include the necessary header


files. Step 2 : Define the buffer size as
1024.
Step 3 : Get the file name which has been created already.
Step 4 : Open the file in read mode.
Step 5 :.Read the contents of the file and store it in the buffer.Step 6
: Print the contents stored in the buffer.
Step 7 : Close the file.
PROGRAM: ls

#include<stdio.h>
#include<dirent.h>
main(int argc, char
**argv)
{
DIR *dp;
struct dirent *link;
dp=opendir(argv[1]);
printf(“\n contents of the directory %s are \n”, argv[1]);
while((link=readdir(dp))!=0)
printf(“%s”,link->d_name);
closedir(dp);
}

OUTPUT:

cCc list.c
./a.out os
CONTENTS OF THE DIRECTORY OS ARE
Priority.c

5
Robin.c
copy

5
PROGRAM: grep

#include<stdio.h>
#include<string.h>
#define max 1024
void usage()
{
printf(“usage:\t. /a.out filename word \n “);
}
int main(int argc, char *argv[])
{
FILE *fp;
char fline[max];
char *newline;
int count=0;
int occurrences=0;
if(argc!=3)
{
usage();
exit(1);
}
if(!(fp=fopen(argv[1],”r”)))
{
printf(“grep: couldnot open file : %s \n”,argv[1]);
exit(1);
}
while(fgets(fline,max,fp)!=NULL)
{
count++;
if(newline=strchr(fline, ‘\n’))
*newline=’\0’;
if(strstr(fline,argv[2])!=NULL)
{

5
printf(“%s: %d %s \n”, argv[1],count, fline);
occurrences++;
}
}
OUTPUT:

CAT>SAMP
ONE
ONE TWO
THREE FOUR
Cc grep.c
./a.out samp one
Samp:1 one
Samp:2 one two

RESULT:

Thus the program was executed successfully

5
Ex. No: 4
SHELL PROGRAMMING
Date:

AIM:

To practice writing shell programs with UNIX.

PROCEDURE FOR WRITING SHELL PROGRAMS:

Step-1: Open Putty Server.


Step-2: Type sh in the command prompt. Shell mode will be opened.
Step-3: Then type the shell commands such as date, echo, expr, etc., and see the output.
Step-4: Also we can type the C programs using shell programming with the help of vi
editor.
Step-5: To open a C program, type vi <space> filename.c in the shell prompt. A new window
will be opened. Press insert key in the keyboard to start typing the program.
Step-6: Once the program creation is completed, press esc key, then type :wq. ‘w’ indicatesthe
server to save the program and ‘q’ indicates to quit the vi editor window and goto shell
prompt.

Step-7: To compile the C program, type cc<space>filename.c. ‘c’ indicates ‘c compiler’.

Step-8: To run the C program, give ./a.out. This refers to run the object file that was created
recently.

SIMPLE COMMANDS:

[staffit@it ~]$ sh

sh-3.2$ echo "IT"

sh-3.2$ name="ITDEPT"

sh-3.2$ echo $name

sh-3.2$ num=137 %Assigns the variable num to the value 137%

sh-3.2$ expr $num+3

sh-3.2$ date %Dispalys the current date and time%

sh-3.2$ cal %Displays the current month calendar%

5
C Program to find the given number is even or odd.

[staffit@it ~]$ vi even.c


#include<stdio.h>
int main()
{
int n;
printf(“\n Enter the
number:”); scanf(“%d”,&n);
if(n%2==0)
printf(“\n The number %d is even”,n);
else
printf(“\n The number %d is odd”,n);
return 0;
}

OUTPUT:
:wq
cc even.c
./a.out
Enter the number: 5
The number 5 is
odd

1. C program to test the number for prime.


[staffit@it ~]$ vi prime.c
#include<stdio.h>
int main()
{
int n,i;
printf(“\n Enter the number:”);
scanf(“%d”,&n);
for(i=2;i<=n-1;i++)
{
5
if(n%i==0)

5
{
printf(“\n The number %d is not a prime number”,n);
break;
}
}
if(i==n)
printf(“\n The number %d is prime”);
return 0;
}
OUTPUT:
:wq
cc prime.c
./a.out
Enter the number: 5
The number 5 is
prime

RESULT:

Thus the shell scripting had been practiced successfully in UNIX Operating System.

5
Ex. No: 5
CPU SCHEDULING ALGORITHMS
Date:
AIM:

To write a C program to implement various CPU scheduling algorithms such as Round


Robin, SJF, FCFS, Priority algorithm for scheduling the processes.

a. ROUND ROBIN ALGORITHM:

DESCRIPTION:
Round Robin algorithm allocates a quantum time so that all the processes gets an equal
opportunity to execute at regular intervals.

ALGORITHM:
Step-1: Create arrays for processes, its burst time, waiting time and turn-around
time. Step-2: Read the quantum time from the user.
Step-3: Check the burst time of each process with the quantum time. If it is lesser than orequal,
then make the burst time to be zero and remove it from the queue.
Step-4: Else reduce the burst time by quantum and again put it in to the same queue. Repeatthe
steps 3 & 4 until all the processes are executed.

Step-5: The waiting time is calculated as how long does the process is waiting beforegetting
the CPU until it finishes executing.

Step-6: The turn-around time is calculated as the sum of its waiting time plus its burst time.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{ int st[10],bt[10],wt[10],tat[10],n,tq; int
I,count=0,twt=0,ttat=0,temp,sq=0;float
awt=0.0,atat=0.0;
clrscr();
printf(“Enter number of processes:”);
scanf(“%d”,&n);
printf(“\nEnter burst time for sequences:”); for(i=0;i<n;i+
+)
{
scanf(“%d”,&bt[i]);
st[i]=bt[i];

5
}
printf(“\nEnter time quantum:”);
scanf(“%d”,&tq);
while(1)
{
for(i=0,count=0;i<n;i++)
{
temp=tq;
if(st[i]==0)
{
count++;
continue;
}
if(st[i]>=tq)
st[i]=st[i]-tq;
else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}
if(n==count)
break;
}
for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf(“\nProcess_no Burst time Wait time Turn-around time”);
5
5
for(i=0;i<n;i++)
printf(“\n%d %d %d %d”,i+1,bt[i],wt[i],tat[i]);
printf(“\n\nAvg wait time is %f \n Avg turn-around time is %f”,awt,atat);
getch();
}
OUTPUT:

Enter number of processes: 4


Enter burst time for sequences: 5
7
3
9
Enter time quantum: 3
Gantt chart
Process_no Burst time Wait time Turn around time

1 5 9 14
2 7 14 21
3 3 6 9
4 9 15 24
Average wait time is 11.000000
Average turnaround time is
17.000000
b. SHORTEST JOB FIRST ALGORITHM:

DESCRIPTION:
Shortest job first algorithm identifies the process with least burst time and executes it first. In
this case, the processes with shortest burst time gets the highest priority compared to long term
jobs, hence the longest jobs will have to wait indefinitely.

ALGORITHM:

Step-1: Create arrays for processes, its burst time, waiting time and turn-around
time.
Step-2: Sort the processes based on their ascending order of burst
time. Step-3: Execute each process one by one and remove it from the
queue.
Step-4: The waiting time of each process is calculated as the sum of the waiting
time and burst time of its previous process.
Step-5: The turn-around time is calculated as the sum of its waiting time plus its
burst time.

5
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{ char p_name[10][10],temp[10];
int twt=0,ttat=0,wt[10],tat[10],bt[10],i,j,n,tmp;
float awt=0,atat=0;
clrscr();
printf("\nEnter no. of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\nEnter process%d name:",i+1);
scanf("%s",&p_name[i]); printf("\
nEnter burst time:");
scanf("%d",&bt[i]);
wt[i]=0;
tat[i]=0;
}
for(i=0; i<n; i++)
{ for(j=i+1; j<n; j++)
{ if(bt[i]>bt[j])
{ tmp=bt[i];
bt[i]=bt[j];
bt[j]=tmp;
strcpy(temp,p_name[i]);
strcpy(p_name[i],p_name[j]);
strcpy(p_name[j],temp);
}
}
}
for(i=0; i<n; i++)
{ if(i==0)
{ wt[i]=0; tat[i]=bt[i];
}
else
{ wt[i]=wt[i-1]+bt[i-1];
tat[i]=wt[i]+bt[i];
}
twt=twt+wt[i];
ttat=ttat+tat[i];
5
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n\nProcess_Name\t Burst_time \t W_time \t TurnAroundTime ");
for(i=0;i<n;i++)
printf("\n%s \t\t %d \t \t%d \t\t%d",p_name[i],bt[i],wt[i],tat[i]);
printf("\n\nTotal Waiting Time=%d \t Avg Waiting Time = %f ",twt,awt);
printf("\n Total Turn Around Time = %d \t Avg Waiting Time = %f\n",ttat,
atat); getch();
}

OUTPUT:

Enter the number of processes:4


Enter the process name and burst time in ms:

a 6
b 8
c 7
d 3

Gantt chart

ProcessName StartTime BurstTime


d 0.000000 3.000000

a 3.000000 9.000000

c 9.000000 16.000000

b 16.000000 24.000000

Average waiting time of a process=


7.000000 Total running time of process=
24.000000

5
c) FIRST COME FIRST SERVE ALGORITHM:

DESCRIPTION:
FCFS algorithm allocates the CPU to processes based on its arrival order. When one process
is allocated with the CPU, then the remaining processes will have to wait in the ready queue.

ALGORITHM:

Step-1: Create arrays for processes, its burst time, waiting time and turn-around time.
Step-2: Execute each process one by one based on its arrival order and remove it from the queue.
Step-3: The waiting time of each process is calculated as the sum of the waiting time and
burst time of its previous process.
Step-4: The turn-around time is calculated as the sum of its waiting time plus its burst time.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{ char p_name[10][10];
int twt=0,ttat=0,wt[10],tat[10],bt[10],i,n;
float awt=0,atat=0;
clrscr();
printf("\n Enter no of
processes:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter process%d name:\
n",i+1); scanf("%s",&p_name[i]);
printf("\n Enter burst time");
scanf("%d",&bt[i]); wt[i]=0;
tat[i]=0;
}
for(i=0;i<n;i++)
{
if(i==0)
{ wt[i]=0;
tat[i]=wt[i]+bt[i];

5
}
else
{
wt[i]=wt[i-1]+bt[i-1];
tat[i]=bt[i]+wt[i];

}
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n p_name\t p_time\t w_time\t tat\n");for(i=0;i<n;i++)
printf("%s\t%d\t%d\t %d\n",p[i],bt[i],wt[i],tat[i]);
printf("\n Total waiting time=%d \t avg waiting time=%f",twt,awt);
printf("\n Total Turnaround time = %d \t Avg Turnaround time = %f",ttat,
atat); getch();
}
OUTPUT:

Enter the number of processes: 3


Enter the name and burst time of the process:
a 3

b 3

c 12

Gantt chart
ProcessName StartTime BurstTime
a 0.000000 3.000000
b 3.000000 6.000000
c 6.000000 18.000000
Average waiting time of a process=
3.000000 Total running time of process=
18.000000

5
d) PRIORITY SCHEDULING ALGORITHM:

DESCRIPTION:
The processes can be executed based on its priority. There will be an additional queue for
maintaining the priority of the processes. When some processes are already stored in the queue, and
a new process is arriving with high priority such as battery low condition, copying of a data is over,
etc, the new process will be placed as the first element of the queue that is to be dispatched next. The
disadvantage with this algorithm is that the lower priority process will have to wait indefinitely.

ALGORITHM:

Step-1: Create arrays for processes, its priority, its burst time, waiting time and turn around
time. Step-2: Sort the processes based on their priority in ascending order.
Step-3: Execute each process one by one based on its priority and remove it from the queue.
Step-3: The waiting time of each process is calculated as the sum of the waiting time and
burst time of its previous process.
Step-4: The turnaround time is calculated as the sum of its waiting time plus its burst time.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{ char p_name[10][10],temp[10];
int i,j,bt[10],wt[10],tat[10],twt=0,ttat=0,pr[10],tmp,n;
float awt=0,atat=0;
clrscr();
printf("\nEnter no of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\nEnter process%d name:",i+1);
scanf("%s",&p_name[i]); printf("\
nEnter burst time:");
scanf("%d",&bt[i]);
printf("\nEnter priority:");
scanf("%d",&pr[i]);
wt[i]=0;
tat[i]=0;
}

5
for(i=0;i<n-1;i++)
{ for(j=i+1;j<n;j++)
{
if(pr[i]>pr[j])
{ tmp=pr[i];
pr[i]=pr[j];
pr[j]=tmp;
tmp=bt[i];
bt[i]=bt[j];
bt[j]=tmp;
strcpy(temp,p_name[i]);
strcpy(p_name[i],p_name[j]);
strcpy(p_name[j],temp);
}
}
}
for(i=0;i<n;i++)
{ if(i==0)
{ wt[i]=0;
tat[i]=bt[i];
}
else
{ wt[i]=wt[i-1]+bt[i-1];
tat[i]=wt[i]+bt[i];
}
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n\n p_name \t burst_time \t priority \t w_time \t turnaroundtime \n");
for(i=0;i<n;i++)

5
printf(" \n %s \t\t %d \t\t %d \t\t %d \t\t %d "
,p_name[i],bt[i],pr[i],wt[i],tat[i]);
printf("\n\ntotal waiting time=%d \t avg waiting time=%f", twt,awt); printf("\n\
n total turnaroundtime = %d \t avg turn around time = %f", ttat, atat); getch();
}
OUTPUT:

Enter the number of processes:

Enter the process name, priority and burst time:


a 3 10
b 1 1
c 4 2
d 1 1
e 2 5

Gantt chart

Process Name Priority Start Burst

b 1 0.000000 1.000000
e 2 1.000000 6.000000
a 3 6.000000 16.000000
c 4 16.000000 18.000000
d 5 18.000000 19.000000
Average waiting time of a process=

8.200000 Total running time of process=

19.000000

RESULT:
Thus the C program for implementing various CPU scheduling algorithms had been executed
successfully.

5
Ex. No: 6
SEMAPHORES IMPLEMENTATION
Date: (PRODUCER-CONSUMER PROBLEM)

AIM:
To write a C program to implement semaphores as a solution for the producer-consumer
problem.

ALGORITHM:
Step 1: Create a buffer with capacity of 1.
Step 2: First, the producer must place an item in the buffer. If the buffer is already full, then an
error message must be notified to inform the producer to wait for the consumer to
consume the previous item.
Step-3: The consumer can consume the item in the buffer. If the buffer is empty, then the consumer
must wait for the producer to produce the next item.
Step-4: By this way, the producer-consumer processes can execute without any discrepancy.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 1
int n,produced,consumed,buffer[max];
int result,i;
void main()
{ clrscr();
produced=0;
consumed=1;
result=0;
i=0;
while(1)
{ printf("Enter the choice\n");
printf("1.Producer 2.Consumer 3.Exit\n");
scanf("%d",&n);
if(n==3)
exit(0);
else if(n==1)
producer(consumed,buffer[i]);
else if(n==2)
consumer(produced,buffer[i]);
else
exit(0); } }
producer(int consumed,int result)
{ if((consumed==1)&&(i==0))
{ result=result+1;
i++;
5
buffer[i]=result;
produced=1;
printf("\nProduced bufffer=%d\n",buffer[i]);
consumed=0;
return(produced,result);
}
else
printf("\nBuffer is full\n");
}
consumer(int produced,int result)
{ if((produced==1)&&(i>0))
{ consumed=1;
printf("\nConsumed buffer=%d\n",buffer[i]);
produced=0;
i--;
return(consumed,result);
}
else printf("\nBuffer is empty");

OUTPUT:

SEMAPHORES IMPLEMENTATION
(PRODUCER-CONSUMER PROBLEM)

1. PRODUCER
2. CONSUMER
3. EXIT
ENTER YOUR CHOICE 1
producer produces the
item1 ENTER YOUR CHOICE 1
producer produces the
item2 ENTER YOUR
CHOICE 1
producer produces the
item3 ENTER YOUR
CHOICE 1 BUFFER IS
FULL
ENTER YOUR CHOICE 2
consumer consumes item3
ENTER YOUR CHOICE 2
consumer consumes item2
ENTER YOUR CHOICE 2
consumer consumes item1
ENTER YOUR CHOICE 2
BUFFER IS EMPTY
ENTER YOUR CHOICE 3

RESULT:

Thus the C program for implementing semaphores to solve the producer-consumer

5
problem had been executed successfully.

5
EX. NO: 7 IMPLEMENTATION OF SHARED MEMORY USING INTER PROCESS COMM

DATE:

AIM:
To implement the inter-process communication using shared memory.
ALGORITHM:
STEP 1. Start the program
STEP 2. Declare the necessary variables
STEP 3. shmat() and shmdt() are used to attach and detach shared memory segments. They
are prototypes as follows:
void *shmat(int shmid, const void *shmaddr, int
shmflg);int shmdt(const void *shmaddr);

STEP 4. shmat() returns a pointer, shmaddr, to the head of the shared segment associated
with a valid shmid. shmdt() detaches the shared memory segment located at the address
indicated by shmaddr
STEP 5. Shared1.c simply creates the string and shared memory portion.
STEP 6. Shared2.c attaches itself to the created shared memory portion and uses thestring
(printf)
STEP 7. Stop the program.

PROGRAM: They are prototypes as follows:


Shared1.c:(server) void *shmat(int shmid, const void *shmaddr, int shmflg);
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
Shared2.c(client)
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
5
{

5
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid =shmget(key, SHMSZ, 0666)) < 0)
{ perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{ perror("shmat");
exit(1);
}
for (s = shm; *s != NULL; s+
+) putchar(*s);
putchar('\n');
*shm = '*';
exit(0);
}

OUTPUT:
CLIENT:
[oslab@localhost ~]$gcc exp10c.c

[oslab@localhost ~]$./a.out
A
b
c
d
e
f
g
h
i
j
SERVER:
[oslab@localhost ~]$gcc exp10s.c
[oslab@localhost ~]$./a.out
You pressed A
You pressed b
You pressed c
You pressed d
You pressed e
You pressed f
You pressed g
You pressed h
You pressed i
You pressed j

RESULT:
Thus the implementation of Inter process communication using shared memory was
executed and output verified successfully.

5
Ex. No: 8
DEADLOCK AVOIDANCE – BANKER’S ALGORITHM
Date:

AIM:
To write a C program to avoid the occurrence of deadlock using banker’s algorithm.
DESCRIPTION:

Banker’s algorithm is an efficient technique to avoid the occurrence of deadlock in any


operating system. At any instance, it enquires the maximum need of resources by the processes, and
compares it with the available set of resources, and notifies whether the system is in a safe state or
not.

ALGORITHM:

Step-1: Create an 1-Darray for storing the name of the processes and available resource instances.
Step-2: Create 2-D arrays for storing maximum need of the resources, allocated resource details to
each processes and current need of resources by the processes.
Step-3: Calculate the current need of resource instances by subtracting the maximum need and the
allocated resource instances.
Step-4: Now compare the current need with the available resource instances. If the need is lesser or
equal, then allocate the available resources to that process and then release the entire
resource instances from that process and add it to available resource matrix.
Step-5: If any process cannot be allocated with the resources at all, then the algorithm notifies the
user that the system is in a unsafe state.
Step-6: Otherwise, the system is in a safe state to run those processes.

PROGRAM:
#include<stdio.h>
#include<conio.h>
int max[50][10];
int alloc[50][10];
int need[50][10];
int avail[50];
int n,r;
void input();
void show();
void cal();

void main()
{ int i,j;
clrscr();

5
printf("\n***** Banker's Algorithm to avoid occurrence of Deadlock *****\n");
input();
show();
cal();
getch();
}
void input()
{
int i,j;
printf("\nEnter the total no. of Processes:\t");
scanf("%d",&n);
printf("\nEnter the total no. of resources(Eg: printer, CPU, Scanner):\t");
scanf("%d",&r);
printf("\nEnter the Maximum Needful Resource Matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{ scanf("%d",&max[i][j]);
}
}
printf("\nEnter the Allocation Matrix(Previously Allocated Resources):\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{ scanf("%d",&alloc[i][j]);
}
}
printf("\nEnter the Available Instances of each Resource: \n");
for(j=0;j<r;j++)
{
scanf("%d",&avail[j]);
}
}
void show()
{
int i,j;
printf("\nProcess\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]);
5
}
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;
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;
5
5
}
}
}
}
}
}
for(i=0;i<n;i++)
{ if(finish[i]==1)
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:
DEADLOCK AVOIDANCE – BANKER’S ALGORITHM

Enter the no of processes :

5 Enter the no of resources

:3
Enter the Max Matrix for each process :
For process 1 : 7
5
3
For process 2 : 3
2
2
For process 3 : 7

2
For process 4 : 2
2
2
For process 5 : 4
3
5
3
Enter the allocation for each process :

5
For process 1 : 0

For process 2 : 2

For process 3 : 3

For process 4 : 2

For process 5 : 0

Enter the Available Resources :


33
2

Max matrix: Allocation


matrix: 753010
322200
702302
222211
433002

Process 2 runs to completion!


Max matrix: Allocation
matrix: 753010
000000
702302
222211
433002

Process 3 runs to completion!


Max matrix: Allocation
matrix: 753010
000000
000000
222211
433002

Process 4 runs to completion!


Max matrix: Allocation
matrix: 753010
000000
5
5
000000
000000
433002

Process 1 runs to completion!


Max matrix: Allocation
matrix: 000000
000000
000000
000000
433002

Process 5 runs to completion!


The system is in a safe state!!
Safe Sequence : < 2 3 4 1 5 >

Result :
Thus the C program for deadlock using banker’s algorithm had been implemented successfully.

5
Ex. No: 9 DEADLOCK DETECTION ALGORITHM (ALTERNATIVE OF BANK
Date:

AIM:
To write a C program to implement the deadlock detection algorithm.

DESCRIPTION:
Detecting a deadlock is an easy job. It only detects the presence of deadlock after the
deadlock has occurred. An alternative of banker’s algorithm can serve this purpose.

ALGORITHM:
Step-1: Create arrays for storing the current need, available resource instances and theallocated
resource instances.
Step-2: Construct the reource-allocation graph for the scenario.
Step-3: Check the presence of cycles in the graph. If present, then the deadlock hasoccurred.
Step-4: Else, the processes do not create any deadlock and the system is in a safe state.

PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int found,flag,l,p[4][5],tp,tr,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
printf("Enter total no of processes:");
scanf("%d",&tp);
printf("Enter total no of resources:");
scanf("%d",&tr);
printf("Enter claim (Max. Need) matrix:\n");
for(i=0;i<tp;i++)
{
printf("process %d:\n",i);
for(j=0;j<tr;j++)
scanf("%d",&c[i][j]);
}
printf("Enter allocation matrix:\n");
for(i=0;i<tp;i++)
{ printf("process %d:\n",i);
for(j=0;j<tr;j++)

5
scanf("%d",&p[i][j]);
}
printf("Enter resource vector (Total resources):\n");
for(i=0;i<tr;i++)
{ scanf("%d",&r[i]);
}
printf("Enter availability vector (available resources):\n");
for(i=0;i<tr;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=0;i<tp;i++)
{
sum=0;
for(j=0;j<tr;j++)
sum+=p[i][j];
if(sum==0)
{ m[k]=i;
k++;
}
}
for(i=0;i<tp;i++)
{
for(l=0;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=tr;j++)
if(c[i][j]<temp[j])
{
flag=0;
break;
}
}
if(flag==1)
{ m[k]=i;
k++;
for(j=1;j<=tr;j++)
temp[j]+=p[i][j];
}
}
printf("\nDeadlock causing processes are:");
5
for(j=0;j<tp;j++)
{ found=1;
for(i=0;i<k;i++)
{ if(j==m[i])
found=0;
}
if(found==0)
printf("%d\t",j);
}
getch();
}

OUTPUT:
Enter total no of processes: 4 Enter
total no of resources: 5 Enter
claim <Max. Need matrix>
Process 0: 0 1 0 0 1
Process 1: 0 0 1 0 1
Process 2: 0 0 0 0 1
Process 3: 1 0 1 0 1
Enter allocation matrix
Process 0: 1 0 1 1 0
Process 1: 1 1 0 0 0
Process 2: 0 0 0 1 0
Process 3: 0 0 0 0 0
Enter resource vector<Total resources>: 2 2 1 1 1
Enter availability vector<Available resources: 0 0 0 0 1
Deadlock causing processes are:
RESOURCES ALLOCATED NEEDED TOTAL
P1322101221
P2613511102
P3314212102
P4422002420
AVAIL BEFORE AVAIL AFTER
DEADLOCK OCCURED

RESULT:
Thus the C program for detecting deadlocks had been implemented successfully.

5
Ex. No:
10
IMPLEMENTATION THREADING AND SYNCHRONIZATION
APPLICATIONS
Date:

AIM: To implement Threading and Synchronization applications using C-Programming.


Program:
Thread Cretation:
#include <pthread.h>
pthread_attr_t tattr;
pthread_t tid;
extern void *start_routine(void *arg);
void *arg;
int ret;
/* default behavior*/
ret = pthread_create(&tid, NULL, start_routine, arg);
/* initialized with default attributes */
ret = pthread_attr_init(&tattr);
/* default behavior specified*/
ret = pthread_create(&tid, &tattr, start_routine, arg);
Thread Termination:
#include <pthread.h>
pthread_t tid;
int ret;
int status;
/* waiting to join thread "tid" with status */ret
= pthread_join(tid, &status);
/* waiting to join thread "tid" without status */ret
= pthread_join(tid, NULL);
Process 1:
// for WinXp
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
int main()
{
// one process creates the mutex object.
5
HANDLE hMutex;
char * MName = "MyMutex";
hMutex = CreateMutex( NULL,
// no security descriptorFALSE,
// mutex not owned MName); //
object name
if (hMutex == NULL)
printf("CreateMutex(): error: %d.\n", GetLastError());
else
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
printf("CreateMutex(): opened existing %s mutex.\n", MName);
else
printf("CreateMutex(): new %s mutex successfully created.\n", MName);
}
return 0;
}
Process 2:
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
int main()
{
HANDLE hMutex1;
hMutex1 = OpenMutex(
MUTEX_ALL_ACCESS, // request full access
FALSE, // handle not inheritable
MName); // object name
if (hMutex1 == NULL)
printf("OpenMutex(): error: %d.\n", GetLastError());
else
printf("OpenMutex(): %s mutex opened successfully.\n", MName);
return 0;
}
Prcess 3:
#define _WIN32_WINNT 0x0501
41
#include <windows.h>
#include <stdio.h>
int main()
{
// one process creates the mutex
object. HANDLE hMutex;
char * MName = "MyMutex";
hMutex = CreateMutex( NULL,
// no security descriptorFALSE,
// mutex not owned MName); //
object name
if (hMutex == NULL)
printf("CreateMutex(): error: %d.\n", GetLastError());
else
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
printf("CreateMutex(): opened existing %s mutex.\n", MName);
else
printf("CreateMutex(): new %s mutex successfully created.\n", MName);
}
HANDLE hMutex1;
hMutex1 = OpenMutex(
MUTEX_ALL_ACCESS, // request full access
FALSE, // handle not inheritable
MName); // object name
if (hMutex1 == NULL)
printf("OpenMutex(): error: %d.\n", GetLastError());
else
printf("OpenMutex(): %s mutex opened successfully.\n", MName);
return 0;
}
Semaphore (Using Semaphore for Synchronization)
The following example uses the CreateSemaphore() function to illustrate a named-object
creation operation that fails if the object already exists.
// for WinXp
#define _WIN32_WINNT 0x0501
41
#include <windows.h>
#include <stdio.h>
HANDLE CreateNewSemaphore(LPSECURITY_ATTRIBUTES lpsa, LONG cInitial,
LONG cMax, LPTSTR lpszName)
{
HANDLE hSem;
// create or open a named
semaphore. hSem =
CreateSemaphore(
lpsa, // security attributes, NULL = handle cannot be inheritedcInitial,
// initial count
cMax, // maximum count
lpszName); // semaphore name
// close handle, and return NULL if existing semaphore opened.
if (hSem == NULL && GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hSem);
return NULL;
}
else
{
printf("Checking the last error: %d.\n", GetLastError());
printf("CreateNewSemaphore(): New semaphore was created successfully.\n");
}
// if new semaphore was created, return the
handle. return hSem;
}
int main()
{
LPSECURITY_ATTRIBUTES lpsa = NULL;
LONG cInitial =
0; LONG cMax =
10;
LPTSTR lpszName = "MySemaphore";
HANDLE hSemaphore = CreateNewSemaphore(lpsa, cInitial, cMax, lpszName);
return 0;
} 66
Output:
IMPLEMENTATION THREADING AND SYNCHRONIZATION APPLICATIONS
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished

RESULT: Thus the C - program for implementing Threading and Synchronization application was
implemented and output verified using various sample.

66
EX. NO: 11 IMPLEMENTATION OF MEMORY ALLOCATION METHO
DATE:

AIM:
To write a C program to implement the memory management scheme using fixed sized
partitions.

ALGORITHM:
Step 1: Input memory blocks with size and processes with

size. Step 2: Initialize all memory blocks as free.

Step 3: Start by picking each process and check if it can be assigned to current block. Step

4: If size-of-process <= size-of-block if yes then assign and check for next process.Step 5: If

not then keep checking the further blocks.

PROGRAM:
# include<stdio.h>
#include<conio.h>
#define MAXSIZE 25
void printlayout(int[],int);
int firstfit(int[],int,int);
int bestfit(int[],int,int);
void main()
{
int i,a[25],n,req,choice,pos,ch;
clrscr();
printf(“how many segments”);
scanf(“%d”,&n);
for(i=0.,i<n;i++)
{
printf(“segment size”);
scanf(“%d”,&a[i]);
}
loop:
printf(“how much is your requirements”);
scanf(“%d”,&req);
66
66
printf(“/n1.bestfit\n2.firstfir\n3.exit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
pos=bestfit(a,n,req);
break;
case 2:
pos=firstfit(a,n,req);
break;
}
printf(“\t bestfit and firstfit algorithms\n”); printf(“\
n =\n\n”);
printlayout(a,n);
printf(your memory requirement is :%d\n\n”,req);
printf(“\n alloted memory requirement is :%\n\n”,[pos]);
a[pos]=0;
printf(“do you wnat to continue
i/o”); scanf(“%d”&ch);
if(ch==i)
goto loop;
getch();
void printlayout (int a[],int n)
{
int i,j:
printfd(“\t\tmemory free list”);
printf(“\n\t\t \n\n”);
printf(“\t\t~~~\n”); for(i=0;i<n;i+
+)
{
if (a[i]!=0)
{

66
for(j=i:j=<=(a[i]/100);j++)
printf(“\t\t| |\n”);
printf(“\t\t|%d|\n”, a[i]);
printf(“\t\t--|\n”);
}
}
int firstfit(int(int a[],int n,int r)
{
int i;
for(i=o;i<=n;i++)
if(a[i]>=r)
break;
return i;
}
int bestfit(int a[], int n, int r)
{
int b[25],i,j,temp,val;
for(i=0;i<n;i++)
b[i]=a[i];
for(i=0;i<n-1;i++)
for(j=0;j<n-1;j++)
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
for(i=0;i<n;i++)
if(b[i]>=r)
break;
val=b[i];
for(i=0;i<n;i++)
if(a[i]==val)

66
break;
return i;
}

OUTPUT:
How many segments 4
Segment size 500
Segment size 200
Segment size 300
Segment size 400
How much is your memory requirement
200 1.bestfit
2.firstfit
3.exit
Enter your choice 1
Bestfit and firstfit algorithm
____ _
Memory free list
_ _ _ _ _
500
200
300
400
Your memory requirement is:200
Allotted memory region is:200

How much is your memory requirement


250 1.bestfit
2.firstfit
3.exit
Enter your choice 2
Bestfit and firstfit algorithm
____ _
Memory free list
_ _ _ _ _
500
300
400
Your memory requirement is:250
Allotted memory region is:300

RESULT:
Thus the C program to implement the memory management scheme using fixed size
partition was executed and output verified successfully.

66
EX. NO: 12 IMPLEMENTATION OF PAGING USING MEMORY MANA
DATE:

AIM:
To write a C program to implement the memory management scheme using paging.

ALGORITHM:
Step1: Start the program.
Step 2: Enter the page size.
Step3: Enter the logical memory address.
Step 3: Enter the user data.
Step 4: Enter starting position of each page.
Step5: Enter data to which mapping address to be found.
Step 5: Calculate and display the physical address for the corresponding logical
address.Step 7: Stop the program.

PROGRAM:
#include<stdio.h>
void main()
{
int a[20],lmem,pmem,ch,psize,str,b[35],c[10];
int i,j,k,INDEX,page,frame,addr; printf("\
nEnter page size: "); scanf("%d",&psize);
printf("\nEnter logical memory in bytes: ");
scanf("%d",&lmem);
printf("\nEnter physical memory: ");
scanf("%d",&pmem); printf("\nEnter
user data: "); for(i=0;i<lmem;i++)
scanf("%d",&a[i]); for(i=0;i<32;i++)
{
b[i]=-1;
}
for(i=0;i<lmem/psize;i++)
{
printf("\nEnter starting position of each page:");
scanf("%d",&str);
c[i]=str/4; for(j=str,k=i*psize;j<(str+psize),k<(i*psize)
+psize;j++,k++)
{
b[j]=a[k];
}
}
for(i=0;i<pmem;i++)
{
printf("\n%d",b[i]);
}

66
printf("\nEnter dat to which mapping addr to be found: ");
scanf("%d",&ch);
for(i=0;i<lmem;i++)
{
if(ch==a[i])
{ INDEX
=i;
page=INDEX/psize;
frame=c[page];
addr=(frame*psize)+(INDEX%psize);
}
}
printf("\nThe physical addr for %d is %d ",ch,addr);
}

OUTPUT:
[osslab@fosslab ~]$ vi pp.c
[osslab@fosslab ~]$ cc pp.c
[osslab@fosslab ~]$ ./a.out
Enter page size: 4
Enter logical memory in bytes: 3
Enter physical memory: 4
Enter user data: 1
2
3
-1
-1
-1
-1
Enter data to which mapping addr to be found:
3The physical address of 3 is -5430558
[osslab@fosslab
~]$

RESULT:
Thus the C program to implement the memory management scheme using paging
algorithm was executed and output verified successfully.

66
Ex. No: 13
PAGE REPLACEMENT ALGORITHMS
Date:

AIM:
To write a C program to implement the page replacement algorithms such as FIFO, LRU,
and LFU.

a) FIRST IN FIRST OUT ALGORITHM:

DESCRIPTION:

Paging concept fills the block of memory, referred as frame, with pages corresponding to an
application. When the frame is full and a new page is to be loaded into it, this situation is referred as
page fault. In order to reduce the number of pagefaults, several page replacement algorithms have
been introduced. One such algorithm is FIFO. This algorithm replaces the pagers in first in first out
order.

ALGORITHM:

Step-1: Get the number of pages and page numbers required by an application.
Step-2: Get the frame (block) size and initialize the frame array with -1
initially. Step-3: The first three pages can be directly filled with distinct pages.
Step-4: Then the remaining page numbers can be filled in by replacing the pages inFIFO
order. If the page is already present, then there is no need for replacement.
Step-5: Each time a replacement is done, page fault is incremented by
1. Step-6: Print the number of page faults.

PROGRAM:

#include<stdio.h>
#include<conio.h>
int fr[3];
void display();
void main()
{ int i,j,page[20],n;
int flag1=0,flag2=0,pf=0,frsize=3,top=0;
clrscr();
for(i=0;i<3;i++)
{ fr[i]=-1; }
printf("\n Enter the number of pages:");
scanf("%d",&n);
printf("\n Enter the pages to be loaded in order:");
for(i=0;i<n;i++)
{ scanf("%d",&page[i]); }
for(j=0;j<n;j++)
{ flag1=0;
flag2=0;
66
for(i=0;i<n;i++)
{ if(fr[i]==page[j])
{ flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{ for(i=0;i<frsize;i++)
{ if(fr[i]==-1)
{ fr[i]=page[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{ fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}
printf("\n \t Number of page faults : %d
",pf); getch();
}
void display()
{ int i; printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}
OUTPUT:

Enter the number of pages: 10


Enter the pages to be loaded in order: 2 3 2 1 5 2 4 5 3 2

66
b) LEAST RECENTLY USED ALGORITHM:

DESCRIPTION:

Least Recently Used(LRU) algorithm chooses the page that was not accessed for a longtime
to be replaced with a new page.

ALGORITHM:

Step-1: Get the number of pages and page numbers required by an application.
Step-2: Get the frame (block) size and initialize the frame array with -1
initially. Step-3: The first three pages can be directly filled with distinct pages.
Step-4: Then the remaining page numbers can be filled in by replacing the pages in LRUorder.
Step-5: Compare the previous two page numbers with that of the frame pages, if any ofthe
page is not present in frame, then that is the page to be replaced.
Step-6: If the page is already present, then there is no need for replacement.
Step-7: Each time a replacement is done, page fault is incremented by 1.
Step-8: Print the number of page faults.

PROGRAM:
#include<stdio.h>
#include<conio.h>
int fr[3],fs[3];
void display();
void main()
{
int p[20];
int i,j,index,k,l,n,flag1=0,flag2=0,pf=0,frsize=3;
clrscr();
printf("\n Enter the number of pages:");
scanf("%d",&n);
printf("\n Enter the pages numbers in
sequence:"); for(i=0;i<n;i++)
{ scanf("%d",&p[i]); }
for(i=0;i<3;i++)
{ fr[i]=-1; }
for(j=0;j<n;j++)
{
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1;

66
break;
}
}
if(flag1==0)
{ for(i=0;i<3;i++)
{ if(fr[i]==-1)
{ fr[i]=p[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<3;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
{ for(i=0;i<3;i++)
{ if(fr[i]==p[k])
fs[i]=1;
}
}
for(i=0;i<3;i++)
{ if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\n No. of page faults :%d",pf);
getch();
}
void display()
{ int i; printf("\
n");
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
}

OUTPUT:
Enter the number of pages: 10
Enter the page numbers in sequence: 2 3 2 1 5 2 4 5 3 2
66
c) LEAST FREQUENTLY USED ALGORITHM:

DESCRIPTION:

Least Frequently Used(LFU) algorithm chooses the page that was accessed only for lessnumber
of times to be replaced with a new page.

ALGORITHM:

Step-1: Get the number of pages and page numbers required by an application.
Step-2: Get the frame (block) size and initialize the frame array with -1
initially. Step-3: The first three pages can be directly filled with distinct pages.
Step-4: Then the remaining page numbers can be filled in by replacing the pages in LFU
order.
Step-5: A count should be initialized for each distinct page number. Whenever the page fault
occurs, the count of those pages inside the frame are analyzed and the page with
least count is to be replaced.
Step-6: If the page is already present, then there is no need for replacement.
Step-7: Each time a replacement is done, page fault is incremented by 1.
Step-8: Print the number of page faults.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int f,p;
int pages[50],frame[10],hit=0,count[50],time[50],fault=0;
int i,j,page,flag,least,minTime,temp;
clrscr();
printf("Enter no of frames : ");
scanf("%d",&f);
printf("Enter no of pages : ");
scanf("%d",&p);
for(i=0;i<f;i++)
{ frame[i]=-1; }
for(i=0;i<p;i++)
{ count[i]=0; }
printf("Enter page no : \n");
for(i=0;i<p;i++)
{ scanf("%d",&pages[i]); }
printf("\n"); for(i=0;i<p;i+
+)
{ count[pages[i]]++;
time[pages[i]]=i;
flag=1;

66
least=frame[0];
for(j=0;j<f;j++)
{ if(frame[j]==-1 || frame[j]==pages[i])
{ if(frame[j]!=-1)
{ hit++; }
flag=0;
frame[j]=pages[i];
break;
}
if(count[least]>count[frame[j]])
{ least=frame[j]; }
}
if(flag)
{
minTime=50;
for(j=0;j<f;j++)
{
if(count[frame[j]]==count[least] && time[frame[j]]<minTime)
{ temp=j;
minTime=time[frame[j]];
}
}
count[frame[temp]]=0;
frame[temp]=pages[i];
fault++;
}
for(j=0;j<f;j++)
{ printf("%d ",frame[j]); }
printf("\n");
}
printf("\nPage hit = %d",hit);
printf("\n Page Fault = %d",fault);
getch();
}

OUTPUT:
Enter number of frames: 3
Enter no of pages: 10
Enter page no : 2 3 2 1 5 2 4 5 3 2

RESULT:

Thus the C program for implementing various page replacement algorithms had been
executed successfully.
66
Ex. No: 14
FILE ORGANIZATION TECHNIQUES
Date:
AIM:
To write a C program to implement various file organization techniques such as single
level and two level directory structures.

a) Single Level Directory Structure:

DESCRIPTION:

Single level directory refers to having only one folder and the files are simply stored in this
folder. Hence there cannot be more than one file with same name. Here the folder refers to the
directory in UNIX operating system.

ALGORITHM:

Step-1: Create an 2-D array for stroing the directory name and its file
details. Step-2: The file names must be unique within each directory.
Step-3: When the user wants to create another directory, then the OS creates a new array tostore the
file details.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{ int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
clrscr();
printf("\n Enter number of directories:");
scanf("%d",&master);
printf("\nEnter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("\nEnter size(no. of files) of
directories:"); for(i=0;i<master;i++)
scanf("%d",&s[i]); printf("\
nEnter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" \n Directory Name \t Size(no of files) \t File Names \n");
printf("********************************************************\n");

66
for(i=0;i<master;i++)
{ printf("%s\t\t %d \t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf(" %s\n\t\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
getch();
}

OUTPUT:

oslab@localhost ~]$ gcc SLD.c

[oslab@localhost ~]$ ./a.out

enter number of directorios:2

enter names of directories:senthil

prabhu

enter size of directories:7

enter the file names :exp1.c

exp2.c

exp3.c

exp4.c

exp5.c

exp6.c

exp7.c

exp8

exp9

exp10

exp11

exp12

66
exp13

exp14

exp15

directory size filenames


senthil 7 exp1.c

exp2.c

exp3.c

exp4.c

exp5.c

exp6.c

exp7.c

prabhu 8 exp8

exp9

exp10

exp11

exp12

exp13

exp14

exp15

b) Two Level Directory Structure:


DESCRIPTION:

Two-level directory refers to having a main directory with number of subdirectories andfiles.
Two files can have same name when they are present in different subdirectory.

ALGORITHM:

Step-1: Create a structure for directory to hold the subdirectory name, subdirectory files,and
the files to be placed directly in the directory.
Step-2: Get the directory details from the user and store it in the
structure. Step-3: Display the directory details in two-level format.

66
PROGRAM:

#include<stdio.h>
#include<conio.h>
struct st
{ char dname[10];
char sdname[10][10];
char fname[10][10][10];
int ds,sds[10];
}dir[10];
void main()
{ int i,j,k,n;
clrscr();
printf("\nEnter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\nEnter directory %d names:",i+1);
scanf("%s",&dir[i].dname);
printf("\nEnter size(no. of subdirectories) of directories:");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{ printf("\nEnter subdirectory name and size:");
scanf("%s",&dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
{ printf("\nEnter file name:");
scanf("%s",&dir[i].fname[j][k]);
}
}
}
printf("\ndirname\t\tsize(no. of subdirectories)\tsubdirname\t size(no. of files) \t file
names"); printf("\
n****************************************************************
**\n");
for(i=0;i<n;i++)
{ printf("%s \t\t %d",dir[i].dname,dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{ printf("\t\t%s\t\t%d\t",dir[i].sdname[j],dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
printf(" %s\t",dir[i].fname[j][k]);
printf("\n\t\t");
}
printf("\n");
}
66
getch();
}

OUTPUT:

enter number of directories:2


enter directory 1 names:senthil
enter size of directories:2
enter subdirectory name and size:ram 2
enter file name:exp1.c
enter file name:exp2.c
enter subdirectory name and size:raj 2
enter file name:exp3.c
enter file name:exp4.c
enter directory 2 names:prabhu
enter size of directories:2
enter subdirectory name and size:sri 2
enter file name:exp5.c
enter file name:exp6.c
enter subdirectory name and size:guru 2
enter file name:exp7.c
enter file name:exp8.c

dirname size subdirname size files


******************************************************

Senthil 2 ram 2 exp1.c exp2.c


raj 2 exp3.c exp4.c

prabhu 2 sri 2 exp5.c exp6.c


guru 2 exp7.c exp8.c

RESULT:
Thus the C program for implementing the single-level and two-level directory techniqueshad
been executed successfully.

66
Ex. No: 15
FILE ALLOCATION STRATEGIES
Date:
AIM:

To write a C program to implement the file allocation strategies such as sequential,


indexed, and linked type.

a) SEQUENTIAL FILE ALLOCATION:


DESCRIPTION:

In sequential file allocation strategy, the files are stored sequentially. It is similar to the
concept of storing the elements in arrays. The first file will occupy the first free space and the second
file will be allotted the memory following the last byte of the first file. When the subsequent
memory is not free, the previous contents would simply be replaced by this new file. This is the
disadvantage of this strategy.

ALGORITHM:

Step-1: Create an array to store the block length, and number of blocks in each
file. Step-2: Read the number of files from the user.
Step-3: Get the details of the files and store it in the respective arrays.
Step-4: Now the starting block of the second file should be the continuity of the first file.
Repeat this step for all the files.
Step-5: Display the memory arrangement of the required file.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,b[20],sb[20],t[20],x,c[20][20];
char ch='y';
clrscr();
printf("Enter no.of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("Enter no. of blocks occupied by file%d",i+1);
scanf("%d",&b[i]);
printf("Enter the starting block of file
%d",i+1); scanf("%d",&sb[i]);
t[i]=sb[i];
for(j=0;j<b[i];j++)
c[i][j]=sb[i]++;
}
printf("Filename\tStart block\tlength\n");

66
for(i=0;i<n;i++)
printf("%d\t %d \t%d\n",i+1,t[i],b[i]);
do
{
printf("Enter file name:");
scanf("%d",&x);
printf("File name is:%d",x);
printf("length is:%d",b[x-1]);
printf("blocks occupied:");
for(i=0;i<b[x-1];i++)
printf("%4d",c[x-1][i]);
printf("\n Do you wish see the file allocation once again ");
printf("\n Press 'y' for YES and 'n' for NO: ");
ch=getch();
} while(ch=='y');
}

OUTPUT:
Enter no.of files:2
Enter no. of blocks occupied by file1: 4
Enter the starting block of file1: 2
Enter no. of blocks occupied by file2: 10
Enter the starting block of file2: 5
Filename
1
2
Start block
2
5
length
4
10
Enter file name:rajesh
File name is:0 length is:1 blocks occupied: 1

b) INDEXED FILE ALLOCATION:

DESCRIPTION:

In indexed file allocation strategy, the files are stored randomly. An index is created and kept
as an array that stores the address of the starting block of each file. The disadvantage is thatthe index
size is limited and not extendible.

66
ALGORITHM:

Step-1: Create an array to store the index, the block length, and number of blocks in each
file.
Step-2: Read the number of files from the user.
Step-3: Get the details of the files and store it in the respective arrays.
Step-4: Now the starting block of each file will be copied to the index. Repeat this step
for all the files.
Step-5: Display the memory arrangement of the required file along with its index.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{ int n,m[20],i,j,sb[20],b[20][20],x,ch=1;
clrscr();
printf("\nEnter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\nEnter starting block of file%d:",i+1);
scanf("%d",&sb[i]);
printf("\nEnter number of blocks occupied by file
%d:",i+1); scanf("%d",&m[i]);
printf("\nEnter the block numbers of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
}
printf("\nFile\t index\tlength\n");
for(i=0;i<n;i++)
{ printf("%d\t%d\t%d\n",i+1,sb[i],m[i]); }
do
{
printf("\nEnter file name:");
scanf("%d",&x);
printf("\nFile name is:%d\n",x);
i=x-1;
printf("\nIndex is:%d",sb[i]);
printf("\nBlock occupied are:");
for(j=0;j<m[i];j++)
printf("%d ",b[i][j]);
printf("\n do you wish to continue???");
printf("\n Press 1 for Yes and 0 for No");
scanf("%d",&ch);
}while(ch==1);
66
}

OUTPUT:

Enter no. of files:2

Enter starting block and size of file1: 2 5

Enter blocks occupied by file1:10

enter blocks of file1:3

254672647

Enter starting block and size of file2: 3 4

Enter blocks occupied by file2:5

enter blocks of file2: 2 3 4 5 6

File

index length

10

Enter file name: venkat

file name is:12803

Index is:0

Block occupied are: 1

c) LINKED FILE ALLOCATION:

DESCRIPTION:

In linked file allocation strategy, the files are stored randomly but the files are linked
together using linked list data structure. The first node will only be known to the file manager and
the second file will be linked to first one, thrid to second, etc, and hence we could achieve linear
access in random arrangement. This method is more suitable since it is scalable to any number of
files and there is no memory constraint.

66
ALGORITHM:

Step-1: Create arrays to store the block length, and number of blocks in each
file. Step-2: Read the number of files from the user.
Step-3: Get the details of the files and store it in the respective arrays.
Step-4: The first file should be taken as the head node and remaining nodes should beadded at
the end.
Step-5: Display the memory arrangement of the required file.

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
void main()
{ int i,j,n;
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("Enter file name:");
scanf("%s",&f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
scanf("%d",&f[i].block[j]);
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{ printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);
for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
66
}
getch();

}
OUTPUT:
Enter no. of files:2
Enter file name:venkat
Enter starting block:20
Enter no.of blocks:6
Enter block numbers:
4 12
15
45
32
25
Enter file name:rajesh
Enter starting block:12
Enter no.of blocks:5
Enter block numbers:65
4
3
2
File start size block
venkat 20
rajesh 12
6
5
4--->12--->15--->45--->32--->25
6--->5--->4--->3--->2

RESULT :

Thus the C program for implement the file allocation strategies such as sequential,indexed, and linked
type problem had been executed successfully.

66

You might also like