KEMBAR78
OS Lab Manual | PDF | Filename | Directory (Computing)
0% found this document useful (0 votes)
9 views64 pages

OS Lab Manual

The document outlines a series of experiments focused on UNIX commands, system calls, CPU scheduling algorithms, memory allocation strategies, and file organization techniques. It includes detailed descriptions, source code examples, and expected outputs for various programming tasks, such as simulating UNIX commands and implementing scheduling algorithms. The content serves as a practical guide for understanding and applying UNIX and operating system concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views64 pages

OS Lab Manual

The document outlines a series of experiments focused on UNIX commands, system calls, CPU scheduling algorithms, memory allocation strategies, and file organization techniques. It includes detailed descriptions, source code examples, and expected outputs for various programming tasks, such as simulating UNIX commands and implementing scheduling algorithms. The content serves as a practical guide for understanding and applying UNIX and operating system concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

TABLE OF CONTENTS

EXP.NO NAME OF THE EXPERIMENT PAGE.NO


1 Practicing UNIX commands 3-6
Write programs using following UNIX operating 7-9
2 system calls
Fork, getpid, wait
3 Simulate UNIX commands like cp,ls,grep,etc,. 10-13
CPU Scheduling algorithams
A)First Come First Serve(FCFS) 14-15
4 B)Shortest Job First(SJF) 16-17
C)Roundrobin 18-19
D)Priority 20-21
Contiguous Memory Allocation
A)First Fit
22-23
5 B)Best Fit
24-25
C)Worst Fit
26-27
File Allocation strategies
A)Sequential 28-29
6
B)Indexed 30-31
C)Linked 32-33
Simulate paging technique of Memory 34-35
7 Management
File organization Techniques
A)Single Level Directory 56-38
8
B)Two Level Directory 39-42
Page Replacement Algorithms
9 A)First In First Out(FIFO) 43-45
B)Least Recently Used(LRU) 46-48
C)Least Frequently used(LFU) 49-50
10 Simulate Dinning- Philosophers Problem 51-53
Simulate Bankers Algorithm for Deadlock Avoidance 54-59
11 and Prevention
12 Producer-Consumer Problem using Threads 60-62
13 Simulate sleeping barber Problem 63-65
EXPERIMENT:1

Practicing UNIX commands:

AIM: Practice UNIX commands

DESCRIPTION:
Unix is now one of the most commonly used Operating systems used for various purposes such as
Personal use, Servers, Smartphones, and many more. It was developed in the 1970’s at AT& T Labs by
two famous personalities Dennis M. Ritchie and Ken Thompson.
Linux/Unix commands are case-sensitive i.e Hello is different from hello.

Basic unix commands:

1. who : The ‘$ who’ command displays all the users who have logged into the system currently.As
shown above on my system I am the only user currently logged in.The thing tty2 is terminal line the
user is using and the next line gives the current date and time

$ who
Output: harssh tty2 2017-07-18 09:32 (:0)

2. pwd : The ‘$pwd’ command stands for ‘print working directory’ and as the name says,it displays the
directory in which we are currently .
In the output we are harssh directory, which is present inside the home directory

$ pwd
Output: /home/harssh

2. mkdir : The ‘$ mkdir’ stands for ‘make directory’ and it creates a new directory. We have used ‘$ cd’
to get into the newly created directory and again on giving ‘$ pwd’ command, we are displayed with
the new ‘newfolder’ directory.

$ mkdir newfolder
$ cd newfolder
$ pwd
Output: /home/harssh/newfolder

3. rmdir : The ‘$ rmdir’ command deletes any directory we want to delete and you can remember it by
its names ‘rmdir’ which stands for ‘remove directory’.

$ rmdir newfolder

Page 3
4. cd : The ‘$ cd’ command stands for ‘change directory’ and it changes your current directory to the
‘newfolder’ directory.

$ cd newfolder

5. ls : The ‘ls’ command simply displays the contents of a directory.

$ ls
Output: Desktop Documents Downloads Music Pictures Public Scratch Templates Videos

6. touch : The ‘$ touch’ command creates a file(not directory) and you can simple add an extension
such as .txt after it to make it a Text File.

$ touch example
$ ls
Output: Desktop Documents Downloads Music Pictures Public Scratch Templates Videos
example

7. cp : This ‘$ cp ‘ command stands for ‘copy’ and it simply copy/paste the file wherever you want to.In
the above example, we are copying a file ‘file.txt’ from the directory harssh to a new directory new.

$ cp /home/harssh/file.txt /home/harssh/new/

8. mv : The ‘$ mv’ command stands for ‘move’ and it simply move a file from a directory to anothe
directory.In the above example a file named ‘file.txt’ is being moved into a new directory ‘new’

$ mv /home/harssh/file.txt /home/harssh/new

9. rm : The ‘$ rm ‘ command for remove and the ‘-r’ simply recursively deletes file. Try ‘$ rm

filename.txt’ at your terminal

$ rm file.txt

10. chmod : The ‘$ chmod’ command stands for change mode command. As there are many modes in
Unix that can be used to manipulate files in the Unix environment. Basically there are 3 modes that
we can use with the ‘chmod’ command
1. +w (stands for write and it changes file permissions to write)
Page 4
2. +r (stands for read and it changes file permissions to read)
3. +x (generally it is used to make a file executable)

$ chmod +w file.txt
$ chmod +r file.txt
$ chmod +x file.txt

11. cal : The ‘$ cal’ means calendar and it simply display calendar on to your screen.

$ cal
Output : July 2017
Su Mo Tu We Th Fr Sa
1
2345678
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

12. file : The ‘$ file’ command displays the type of file. It displays directory as the output

$ ls
Output: Desktop Documents Downloads Music Pictures Public Scratch Templates Videos
$ file Downloads
Output: Downloads: directory

13. sort : As the name suggests the ‘$ sort’ sorts the contents of the file according to the ASCII rules.

$ sort file

14. man : The ‘$ man’ command stands for ‘manual’ and it can display the in-built manual for most of
the commands that we ever need.In the above example, we can read about the ‘$ pwd’ command.

$ man pwd

15. lpr : The ‘$ lpr’ command send a file to the printer for printing.

$ lpr new.txt

Page 5
16. clear : The ‘$ clear’ command is used to clean up the terminal so that you can type with more

accuracy

$ clear

Page 6
EXPERIMENT 2:

AIM: Write a program using following UNIX operating systemcalls


Fork, getpid, wait

DESCRIPTION:
Fork system call is used for creating a new process, which is called child process, which runs
concurrently with the process that makes the fork() call (parent process). getppid() returns the process
ID of the parent of the current process. A call to wait() blocks the calling process until one of its child
processes exits or a signal is received. After child process terminates, parent continues its execution after
wait system call instruction.

Fork program:

#include<stdio.h>
#include<stdlib.h>
void main()
{
int id;
id=fork();
if(id<0)
{
printf("cannot create the file");
exit(-1);
}
if(id==0)
{
printf("child process");
exit(0);
}
else
{
printf("parent process");
}
}
OUTPUT:

parent process child process

Page 7
getpid PROGRAM:

#include<stdio.h>
#include<stdlib.h>
void main()
{
int pid;
pid=fork();
if (pid==0)
{
printf("\n Child Process\n");
printf("\n Child Process id is %d ",getpid());
printf("\n Its parent process id is %d",getppid());
sleep(5);
printf("Child process after sleep=5\n");
printf("\n Child Process id is %d ",getpid());
printf("\n Its parent process id is %d",getppid());
}
else
{
printf("\nParent process");
sleep(10);
printf("\n Child Process id is %d ",getpid());
printf("\n Its parent process id is %d",getppid());
printf("\nParent terminates\n");
}
}

OUTPUT:

Child Process
Child Process id is 4854
Its parent process id is 4853
Child process after sleep=5
Child Process id is 4854
Its parent process id is 4853Parent process
Child Process id is 4853
Its parent process id is 4848
Parent terminates

Page 8
WAIT PROGRAM:

#include<stdio.h>
#include<stdlib.h>
int i=10;
void main()
{
int pid=fork();
if(pid==0)
{
printf("initial value of i %d \n ",i);
i+=10;
printf("value of i %d \n ",i);
printf("child terminated \n");
}
else
{
wait(0);
printf("value of i in parent process %d",i);
}
}

OUTPUT:

initial value of i 10
value of i 20
child terminated
value of i in parent process 10

Page 9
EXPERIMENT 3:

AIM: Simulate UNIX commands like cp,ls,grep ect,.

DESCRIPTION:
cp- copy- it is used to copying contents from one file to another file.
Syntax:
cp Source Destination
ls-list- its used to list all file names in the directory.
Syntax:
ls
grep-The grep filter searches a file for a particular pattern of characters, and displays all lines that contain
that pattern.
Syntax:
grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers

PROGRAM FOR CP AND LS COMMANDS:

#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#define DATA_SIZE 1000
void createf()
{ char data[DATA_SIZE];
char n[100];
FILE * fPtr;
int i;
printf("create 2 files \nfile1: with data \nfile2: without data for copying\n");
for ( i=0;i<2;i++){
printf("enter a file name:");
gets(n);
fPtr = fopen(n,"w");
if(fPtr == NULL)
{ printf("Unable to create file.\n");
exit(EXIT_FAILURE);
}
printf("Enter contents to store in file : \n");
fgets(data, DATA_SIZE, stdin);
fputs(data, fPtr);
fclose(fPtr);
printf("File created and saved successfully. ?? \n");
Page 10
}
}
void copyfun(){
char ch, source_file[20], target_file[20];
FILE *source, *target;
printf("Enter name of file to copy\n");
gets(source_file);
source = fopen(source_file, "r");
if (source == NULL)
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
printf("Enter name of target file\n");
gets(target_file);
target = fopen(target_file, "w");
if (target == NULL)
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(source)) != EOF)
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
fclose(target);
}
void lsandgrep(){
char fn[10],pat[10],temp[200];
FILE *fp;
char dirname[10];
DIR*p;
struct dirent *d;
printf("Enter directory name\n");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find directory");
exit(0);
}
while(d=readdir(p))
printf("%s\n",d->d_name);
}
int main()
{
Page 11
createf();
copyfun();
lsandgrep();
}

INPUT & OUTPUT:


create 2 files
file1: with data
file2: without data for copying
enter a file name:ha
Enter contents to store in file :
vjhsnknkvljijolk
File created and saved successfully. ??
enter a file name:ka
Enter contents to store in file :

File created and saved successfully. ??


Enter name of file to copy
ha
Enter name of target file
ka
File copied successfully.
Enter directory name
PROJECT
.
..
COUNT_LINE.c
COUNT_LINE.txt
fsearch.c
fsearch.exe
LINE.c
LINE.exe
LINE.txt
tn.txt

Page 12
PROGRAM FOR GREP COMMAND:

#include<stdio.h>
#define MAX_FILE_NAME 100
#include<conio.h>
int main()
{
FILE *fp;
int count = 0;
char filename[MAX_FILE_NAME];
char c;
printf("Enter file name: ");
scanf("%s", filename);

fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n')
count = count + 1;
fclose(fp);
printf("The file %s has %d lines\n ", filename, count);
getch();
return 0;
}

INPUT &OUTPUT:

Enter file name: ha


The file ha has 1 lines

Page 13
EXPERIMENT NO.4

CPU SCHEDULING ALGORITHMS

A).FIRST COME FIRST SERVE:

AIM :To write a c program to simulate the CPU scheduling algorithm First Come First
Serve(FCFS)

DESCRIPTION:
To calculate the average waiting time using the FCFS algorithm first the waiting time of
the first process is kept zero and the waiting time of the second process is the burst time of
the first process and the waiting time of the third process is the sum of the burst times of
the first and the second process and so on. After calculating all the waiting times the
average waiting time is calculated as the average of all the waiting times. FCFS mainly
says first come first serve the algorithm which came first will be served first.

SOURCECODE:

#include<stdio.h>
#include<conio.h>
main()
{
int bt[20],wt[20],tat[20],i,n;
float wtavg,tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process%d--",i);
scanf("%d",&bt[i]);
}
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("\tPROCESS\tBURSTTIME\tWAITINGTIME\tTURNAROUNDTIME\n");
for(i=0;i<n;i++)
printf("\n\tP%d\t\t%d\t\t%d\t\t%d",i,bt[i],wt[i],tat[i]);
printf("\nAverageWaitingTime--%f",wtavg/n);
printf("\nAverageTurnaround Time-- %f",tatavg/n);
getch();
}

Page 14
INPUT
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 BURSTTIME WAITINGTIME TURNAROUND
TIME
P0 24 0 24
P1 3 24 27
P2 3 27 30
AverageWaiting Time-- 17.000000
AverageTurnaroundTime--27.000000

Page 15
B).SHORTEST JOB FIRST:

AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first
(Non-Preemption)

DESCRIPTION:
To calculate the average waiting time in the shortest job first algorithm the sorting of the
process based on their burst time in ascending order then calculate the waiting time of each
process as the sum of the bursting times of all the process previous or before to that
process.

SOURCECODE :
#include<stdio.h>
#include<conio.h>
main()
{
int p[20],bt[20],wt[20],tat[20],i,k,n,temp;
float wtavg,tatavg;
printf("\nEnter the number of processes--");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d--",i);
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=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\tPROCESS\tBURST TIME\tWAITINGTIME\tTURNAROUNDTIME\n");
for(i=0;i<n;i++)
printf("\n\tP%d\t\t%d \t\t%d\t\t%d",p[i],bt[i],wt[i], tat[i]);
printf("\nAverageWaitingTime--%f",wtavg/n);
printf("\nAverageTurnaroundTime--%f",tatavg/n);
getch();
}
Page 16
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 WAITINGTIME TURNAROUNDTIME

P3 3 0 3
P0 6 3 9
P2 7 9 16
P1 8 16 24
AverageWaitingTime--7.000000
AverageTurnaroundTime--13.000000

Page 17
C).ROUNDROBIN:

AIM: To simulate the CPU scheduling algorithm round-robin.

DESCRIPTION:
To aim is to calculate the average waiting time. There will be a time slice, each process
should be executed within that time-slice and if not it will go to the waiting states of first
check whether the burst time is less than the time-slice. If it is less than .If it is greater
than the burst-time then subtract the timeslot from the actual burst time and increment it
by time-slot and the loop continues until all the processes are completed.

SOURCE CODE

#include<stdio.h>
main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes--");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process%d--",i+1);
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];
Page 18
}
printf("\nTheAverageTurnaroundtimeis-- %f",att/n);
printf("\nTheAverageWaitingtimeis--%f",awt/n);
printf("\n\tPROCESS\tBURST TIME\tWAITINGTIME\tTURNAROUNDTIME\n");
for(i=0;i<n;i++)
printf("\tP%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 process1--24

Enter Burst Time for process2--3

Enter Burst Time for process3--3

Enter the size of time slice--4

OUTPUT:

TheAverageTurnaroundtimeis-- 15.666667
TheAverageWaitingtimeis--5.666667
PROCESS BURST TIME WAITINGTIME TURNAROUNDTIME
P1 24 6 30
P2 3 4 7
P3 3 7 10

Page 19
D).PRIORITY:

AIM: To write a c program to simulate the CPU scheduling priority algorithm.

DESCRIPTION:

To calculate the average waiting time in the priority algorithm, sort the burst times
according to their priorities and then calculate the average waiting time of the processes.
The waiting time of each process is obtained by summing up the burst times of all the
previous processes.

SOURCECODE:

#include<stdio.h>
main()
{
int p[20],bt[20],pri[20],wt[20],tat[20],i,k, n,temp;
float wtavg,tatavg;
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=bt[i];
bt[i]=bt[k];
bt[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];

wtavg=wtavg+ wt[i];
tatavg=tatavg+tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURSTTIME\tWAITINGTIME\tTURNAROUNDTIME");
for(i=0;i<n;i++)

Page 20
printf("\nP%d\t\t%d\t\t%d\t\t%d\t\t%d",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverageWaitingTimeis---%f",wtavg/n);
printf("\nAverageTurnaroundTimeis--- %f",tatavg/n);
getch();
}

INPUT

Enter the number of processes --- 5


Enter the Burst Time & Priority of Process 0---10 3
Enter the Burst Time & Priority of Process 1---1 1
Enter the Burst Time & Priority of Process 2---2 4
Enter the Burst Time & Priority of Process 3---1 5
Enter the Burst Time & Priority of Process 4---5 2
Enter the Burst Time & Priority of Process 4---5 2

OUTPUT

PROCESS PRIORITY BUSTIME WAITINGTIME TURN AROUND TIME


P1 1 1 0 1
P4 2 5 1 6
P0 3 10 6 16
P2 4 2 16 18
P3 5 1 18 19
AverageWaitingTimeis---8.200000
AverageTurnaroundTimeis--- 12.000000

VIVAQUESTIONS
1) Define the following
a) Turn around time b)Waiting time c)Burst time d)Arrival time
2) What is meant by process scheduling?
3) What are the various states of process?
4) What is the difference between preemptive and non-preemptive scheduling
5) What is meant by time slice?
6) What is round robin scheduling?

Page 21
EXPERIMENT 5:

MEMORYALLOCATIONTECHNIQUES

AIM: To Write a C program to simulate the following contiguous memory allocation techniques
a) First-fit b)Best-fit c)Worst-fit

DESCRIPTION
One of the simplest methods fo rmemory allocation is to divide memory into several fixed-sized
partitions.Each partition may contain exactly one process. In this multiple-partition method,when a
partitionis free, a process is selected from the input queue an disloaded into the free partition.When the
process terminates, the partition becomes available for another process. The operating system keeps at
able indicating which parts of memory are available and which are occupied.Finally,when a process
arrives and needs memory,a memory section large enough for this process is provided.When it is time
to load or swap a process into main memory,and if there is more than one free block of memory of
sufficient size, then the operating system must decide which free block to allocate.Best-fit strategy
chooses the block that is closest in size to the request.First-fit chooses the first available block that is
large enough.Worst-fit chooses the largest available block.

FIRST FIT:

#include<stdio.h>
#define max 25

void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
printf("\n\tMemory Management Scheme-First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block%d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files:-\n");
for(i=1;i<=nf;i++)
{
printf("File%d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
Page 22
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}

INPUT:
Memory Management Scheme-First Fit
Enter the number of blocks:3
Enter the number of files:2

Enter the size of the blocks:-


Block1:5
Block2:2
Block3:7
Enter the size of the files:-
File1:1
File2:4

OUTPUT:
File_no: File_size: Block_no: Block_size: Fragement
1 1 1 5 4
2 4 3 7 3

Page 23
BEST FIT:

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the sizeof the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block%d:",i);
scanf("%d",&b[i]);
}
printf("Enter the sizeof the files:-\n");
for(i=1;i<=nf;i++)
{
printf("File%d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;
lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFileNo\tFileSize\tBlockNo\tBlockSize\tFragment");
for(i=1;i<=nf&&ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
Page 24
INPUT:

Enter the number of blocks:3


Enter the number of files:2

Enter the size of the blocks:-


Block1:5
Block2:2
Block3:7
Enter the size of the files:-
File1:1
File2:4

OUTPUT:

FileNo FileSize BlockNo BlockSize Fragment


1 1 2 2 1
2 4 1 5 1

Page 25
WORST-FIT:
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
printf("\n\tMemory Management Scheme-Worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the sizeof the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block%d:",i);
scanf("%d",&b[i]);
}
printf("Enter the sizeof the files:-\n");
for(i=1;i<=nf;i++)
{
printf("File%d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)//ifbf[j]isnotallocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
Page 26
INPUT:

Memory Management Scheme-worst Fit


Enter the number of blocks:3
Enter the number of files:2

Enter the size of the blocks:-


Block1:5
Block2:2
Block3:7
Enter the size of the files:-
File1:1
File2:4

OUTPUT:

FileNo FileSize BlockNo BlockSize Fragment


1 1 3 7 6
2 4 1 5 1

Page 27
EXPERIMENT 6:

FILE ALLOCATION STRATEGIES:

AIM: Write a C program to simulate the following file allocation strategies.


a) Sequential b)Linked c))Indexed

DESCRIPTION

A file is a collection of data, usually stored on disk. As a logical entity, a file enables to divided ata into
meaningful groups .As a physical entity, a file should be considered in term so fits organization. The
term "file organization" refers to the way in which data is stored in a file and, consequently, the
method(s) by which it can be accessed.

SEQUENTIAL FILE ALLOCATION

In this file organization, the records of the file are stored one after another both physically and
logically. That is, record with sequence number 16 is located just after the 15th record. A record of a
sequential file can only be accessed by reading all the previous records.

LINKED FILE ALLOCATION

With linked allocation, each file is a linked list of disk blocks; the disk blocks may be scattered
anywhere on the disk. The directory contains a pointer to the first and last blocks of the file. Each block
contains a pointer to the next block.

INDEXED FILE ALLOCATION

Indexed file allocation strategy brings all the pointers together into one location: an index block. Each
file has its own index block, which is an array of disk-block addresses. The ith entry in the index block
points to the ith block of the file. The directory contains the address of the index block. To find and read
the ith block, the pointer in the ith index-block entry is used.

PROGRAM:

SEQUENTIAL FILE ALLOCATION:

#include<stdio.h>
#include<conio.h>
struct fileTable
{
char name[20];
int sb,nob;
}ft[30];
char name[20];
int sb,nob;
void main()
{
int i,j,n;
char s[20];
printf("Enter no of files :");
scanf("%d",&n);
Page 28
for(i=0;i<n;i++)
{
printf("\nEnter file name%d :",i+1);
scanf("%s",ft[i].name);
printf("Enter starting block of file%d :",i+1);
scanf("%d",&ft[i].sb);
printf("Enter no of blocks in file%d:",i+1);
scanf("%d",&ft[i].nob);
}
printf("\nEnter the file name to be searched--");
scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s,ft[i].name)==0)
{
break;
}
if(i==n)
printf("\nFileNotFound");
else
{
printf("\nFILENAME STARTBLOCK NOOFBLOCKS BLOCKSOCCUPIED\n");
printf("\n%s\t\t%d\t\t%d\t",ft[i].name,ft[i].sb,ft[i].nob);
for(j=0;j<ft[i].nob;j++)
printf("%d,",ft[i].sb+j);
}
getch();
}

INPUT:
Enter no of files :3

Enter file name1 :A


Enter starting block of file1 :85
Enter no of blocks in file1:6

Enter file name2 :B


Enter starting block of file2 :40
Enter no of blocks in file2: 3

Enter file name3 :C


Enter starting block of file3 :60
Enter no of blocks in file3:3

Enter the file name to be searched--C

OUTPUT:
FILENAME STARTBLOCK NOOFBLOCKS BLOCKSOCCUPIED

C 60 3 60,61,62,
Page 29
LINKED FILE ALLOCATION:

#include<stdio.h>
#include<conio.h>
struct fileTable
{
char name[20];
int nob;
struct block *sb;
}ft[30];
struct block
{
int bno;
struct block *next;
};
void main()
{
int i,j,n;
char s[20];
struct block *temp;
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter file name%d :",i+1);
scanf("%s",ft[i].name);
printf("Enter no of blocks in file%d:",i+1);
scanf("%d",&ft[i].nob);
ft[i].sb=(struct block*)malloc(sizeof(struct block));
temp=ft[i].sb;
printf("Enter the blocks of the file:");
scanf("%d",&temp->bno);
temp->next=NULL;
for(j=1;j<ft[i].nob;j++)
{
temp->next=(struct block*)malloc(sizeof(struct block));
temp=temp->next;
scanf("%d",&temp->bno);
}
temp->next=NULL;
}
printf("\nEnter the file name to be searched--");
scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s,ft[i].name)==0)
break;
if(i==n)
printf("\nFileNotFound");
else
Page 30
{
printf("\nFILENAMENOOFBLOCKSBLOCKSOCCUPIED");
printf("\n%s\t\t%d\t",ft[i].name,ft[i].nob);
temp=ft[i].sb;
for(j=0;j<ft[i].nob;j++)
{
printf("%d=>",temp->bno);
temp=temp->next;
}
}
getch();
}

INPUT:

Enter no of files :2

Enter file name1 :A


Enter no of blocks in file1:2
Enter the blocks of the file:3
4
Enter file name2 :B
Enter no of blocks in file2:3
Enter the blocks of the file:1
3
2
Enter the file name to be searched--B

OUTPUT:

FILENAME NOOFBLOCKS BLOCKSOCCUPIED


B 3 1=>3=>2=>

Page 31
INDEXED FILE ALLOCATION:

#include<stdio.h>
#include<conio.h>
struct fileTable
{
char name[20];
int nob,blocks[30];
}ft[30];
void main()
{
int i,j,n;
char s[20];
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter file name%d :",i+1);
scanf("%s",ft[i].name);
printf("Enter no of blocks in file%d:",i+1);
scanf("%d",&ft[i].nob);
printf("Enter the blocks of the file:");
for(j=0;j<ft[i].nob;j++)
scanf("%d",&ft[i].blocks[j]);
}
printf("\nEnter the filename to be searched--");
scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s,ft[i].name)==0)
break;
if(i==n)
printf("\nFileNotFound");
else
{
printf("\nFILENAMENOOFBLOCKSBLOCKSOCCUPIED");
printf("\n%s\t\t%d\t",ft[i].name,ft[i].nob);
for(j=0;j<ft[i].nob;j++)
printf("%d,",ft[i].blocks[j]);
}
getch();
}

Page 32
INPUT:

Enter the filename to be searched--A


Enter file name1 :A
Enter no of blocks in file1:4
Enter the blocks of the file:22
33
44
55
Enter file name2 :B
Enter no of blocks in file2:2
Enter the blocks of the file:66
77

OUTPUT:

FILENAME NOOFBLOCKS BLOCKSOCCUPIED


A 4 22,33,44,55,

Page 33
EXPERIMENT 7:

AIM: Write a C program to simulate paging technique of memory management.

DESCRIPTION
In computer operating systems, paging is one of the memory management schemes by which a computer
stores and retrieves data from the secondary storage for use in main memory. In the paging memory-
management scheme, the operating system retrieves data from secondary storage in same-size blocks
called pages. Paging is a memory-management scheme that permits the physical address space a process
to be non contiguous. The basic method for implementing paging involves breaking physical memory into
fixed-sized blocks called frames and breaking logical memory into blocks of the same size called
pages.When a process is to be executed, its pages are loaded into any available memory frames from their
source

PROGRAM:

#include<stdio.h>
#include<conio.h>
main()
{
int ms,ps,nop,np,rempages,i,j,x,y,pa,offset;
int s[10],fno[10][20];
printf("\nEnter the memory size--");
scanf("%d",&ms);
printf("\nEnter the pagesize--");
scanf("%d",&ps);
nop=ms/ps;
printf("\nTheno.ofpagesavailableinmemoryare--%d",nop);
printf("\nEnter number of processes--");
scanf("%d",&np);
rempages=nop;
for(i=1;i<=np;i++)
{
printf("\nEnterno.ofpagesrequiredforp[%d]--",i);
scanf("%d",&s[i]);
if(s[i]>rempages)
{
printf("\nMemory is Full");
break;
}
rempages=rempages-s[i];
printf("\nEnter pagetable for p[%d]---",i);
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnter LogicalAddress to find PhysicalAddress");
printf("\nEnter process no. and page number and offset--");
scanf("%d%d%d",&x,&y,&offset);
if(x>np||y>=s[i]||offset>=ps)
printf("\nInvalid Processor Page Number or offset");
else
{
Page 34
pa=fno[x][y]*ps+offset;
printf("\nThePhysicalAddressis--%d",pa);
}
getch();
}

INPUT& OUTPUT:

Enter the memory size--1000

Enter the pagesize--100

Theno.ofpagesavailableinmemoryare--10
Enter number of processes--3

Enterno.ofpagesrequiredforp[1]--4

Enter pagetable for p[1]---8


6
9
5

Enterno.ofpagesrequiredforp[2]--5

Enter pagetable for p[2]---1


4
5
7
3

Enterno.ofpagesrequiredforp[3]--5

Memory is Full
Enter LogicalAddress to find PhysicalAddress
Enter process no. and page number and offset--2 3 60

ThePhysicalAddressis--760

Page 35
EXPERIMENT 8:

FILE ORGANIZATION TECHNIQUES:

AIM: Write a C program to simulate the following file organization techniques


a) Single level directory b)Two level directory
DESCRIPTION

The directory structure is the organization of files into a hierarchy of folders. In a single-level directory
system, all the files are placed in one directory. There is a root directory which has all files. It has a
simple architecture and there are no subdirectories. Advantage of single level directory system is that it
is easy to find a file in the directory. In the two-level directory system, each user has own user file
directory(UFD). The system maintains a master block that has one entry for each user. This master
block contains the addresses of the directory of the users. When a user job starts or a user logs in, the
system's master file directory (MFD)is searched. When a user refers to a particular file, only his own
UFD is searched. This effectively solves the name collision problem and isolates users from one
another. Hierarchical directory structure allows users to create their own subdirectories and to organize
their files accordingly. A tree is the most common directory structure. The tree has a root directory, and
every file in the system has a unique path name. A directory(or sub directory) contains a set of files or
sub directories.
PROGRAM:

SINGLE LEVEL DIRECTORY:

#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir;
void main()
{
int i,ch;
char f[30];
dir.fcnt=0;
printf("\nEnter name of directory --");
scanf("%s",dir.dname);
while(1)
{
printf("\n\n1.CreateFile\t2.DeleteFile\t3.SearchFile\n4.DisplayFiles\t5.Exit\nEnteryourchoice--");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnterthenameofthefile--");
scanf("%s",dir.fname[dir.fcnt]);
dir.fcnt++;
break;
case 2:printf("\nEnterthenameofthefile--");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
Page 36
if(strcmp(f,dir.fname[i])==0)
{
printf("File%sisdeleted",f);
strcpy(dir.fname[i],dir.fname[dir.fcnt-1]);
break;
}
}
if(i==dir.fcnt)
printf("File%snotfound",f);
else
dir.fcnt--;
break;
case 3:printf("\nEnterthenameofthefile--");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f,dir.fname[i])==0)
{
printf("File%sisfound",f);
break;
}
}
if(i==dir.fcnt)
printf("File%snotfound",f);
break;
case 4:if(dir.fcnt==0)
printf("\nDirectoryEmpty");
else
{
printf("\nTheFilesare--");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]);
}
break;
default:exit(0);
}
}
getch();
}

INPUT AND OUTPUT:

Enter name of directory --CSE


1.CreateFile 2.DeleteFile 3.SearchFile
4.DisplayFiles 5.Exit
Enteryourchoice--1
Enterthenameofthefile--A

Page 37
1.CreateFile 2.DeleteFile 3.SearchFile
4.DisplayFiles 5.Exit
Enteryourchoice--1

Enterthenameofthefile--B

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--1

Enterthenameofthefile--C

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--4

TheFilesare-- A B C

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--2

Enterthenameofthefile--B
FileBisdeleted

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--4

TheFilesare-- A C

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--3

Enterthenameofthefile--A
FileAisfound

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--3

Enterthenameofthefile--N
FileNnotfound

1.CreateFile 2.DeleteFile 3.SearchFile


4.DisplayFiles 5.Exit
Enteryourchoice--5
Page 38
TWO LEVEL DIRECTORY:

#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30],d[30];
dcnt=0;
while(1)
{
printf("\n\n1.CreateDirectory\t2.CreateFile\t3.DeleteFile\n4.SearchFile\t\t5.Display\t6.Exit\t");
scanf("%d",&ch);
switch(ch)
{
printf("Enter your choice-- ");
case 1:printf("\nEnter name of directory--");
scanf("%s",dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2:printf("\nEnter name of the directory--");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enternameofthefile --");
scanf("%s",dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("Filecreated");
break;
}
if(i==dcnt)
printf("Directory%snotfound",d);
break;
case 3:printf("\nEnter name of the directory--");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enternameofthefile --");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
Page 39
{
if(strcmp(f,dir[i].fname[k])==0)
{
printf("File%sisdeleted",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File%snotfound",f);
goto jmp;
}
}
printf("Directory%snotfound",d);jmp:
break;
case 4:printf("\nEnternameofthedirectory--");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enterthenameofthefile--");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f,dir[i].fname[k])==0)
{
printf("File%sisfound",f);
goto jmp1;
}
}
printf("File%snotfound",f);
goto jmp1;
}
}
printf("Directory%snotfound",d);jmp1:
break;
case 5:if(dcnt==0)
printf("\nNoDirectory's");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
Page 40
break;
default:exit(0);
}
}
getch();
}

INPUT&OUTPUT:

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 1

Enter name of directory--SVCK


Directory created

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 1

Enter name of directory--CSE


Directory created

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 5

Directory Files
SVCK
CSE

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 2

Enter name of the DIRECTORY--SVCK


Enternameofthefile --KADAPA
Filecreated

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 2

Enter name of the DIRECTORY--CSE


Enternameofthefile --BRANCH
Filecreated

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 5

Directory Files
SVCK KADAPA
CSE BRANCH
Page 41
1.CreateDirectory 2.CreateFile 3.DeleteFile
4.SearchFile 5.Display 6.Exit Enter your choice-- 3

Enter name of the directory--SVCK


Enternameofthefile --KADAPA
FileKADAPAisdeleted

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 5

Directory Files
SVCK
CSE BRANCH

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 4

Enternameofthedirectory--SVCK
Enterthenameofthefile--KADAPA
FileKADAPAnotfound

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 4

Enternameofthedirectory--CSE
Enterthenameofthefile--BRANCKH
FileBRANCHisfound

1.CreateDirectory 2.CreateFile 3.DeleteFile


4.SearchFile 5.Display 6.Exit Enter your choice-- 6

Page 42
EXPERIMENT 9:

PAGE REPLACEMENT ALGORITHMS:

AIM: Write a C program to simulate page replacement algorithms


a) FIFO b)LRU c) LFU

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 pag ewas brought into memory. When apage 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 use for the longest period of time. Least
frequently used(LFU) page-replacement algorithm requires that the page with the smallest count be
replaced. There a son for this selection is that an actively used page should have a large reference count.

PROGRAM:

FIFO:

#include<stdio.h>
#include<conio.h>
main()
{
int i,j,k,f,pf=0,count=0,rs[25],m[10],n;
printf("\nEnterthelengthofreferencestring--");
scanf("%d",&n);
printf("\nEnterthereferencestring--");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\nEnterno.offrames--");
scanf("%d",&f);
for(i=0;i<f;i++)
m[i]=-1;
printf("\nThePageReplacementProcessis--\n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
if(m[k]==rs[i])
break;
}
if(k==f)
{
m[count++]=rs[i];
pf++;
Page 43
}
for(j=0;j<f;j++)
printf("\t%d",m[j]);
if(k==f)
printf("\tPFNo.%d",pf);
printf("\n");
if(count==f)
count=0;
}
printf("\nThenumberofPageFaultsusingFIFOare%d",pf);
getch();
}

OUTPUT:

Enterthelengthofreferencestring--20
Enterthereferencestring--7
0
1
2
0
3
0
4
2
3
0
3
2
1
2
0
1
7
0
1

Enterno.offrames--3
ThePageReplacementProcessis--
7 -1 -1 PFNo.1
7 0 -1 PFNo.2
7 0 1 PFNo.3
2 0 1 PFNo.4
2 0 1
2 3 1 PFNo.5
2 3 0 PFNo.6
4 3 0 PFNo.7
4 2 0 PFNo.8
4 2 3 PFNo.9
Page 44
0 2 3 PFNo.10
0 2 3
0 2 3
0 1 3 PFNo.11
0 1 2 PFNo.12
0 1 2
0 1 2
7 1 2 PFNo.13
7 0 2 PFNo.14
7 0 1 PFNo.15

ThenumberofPageFaultsusingFIFOare15

Page 45
LRUPAGEREPLACEMENTALGORITHM:

#include<stdio.h>
#include<conio.h>
main()
{
int i,j,k,min,rs[25],m[10],count[10],flag[25],n,f,pf=0,next=1;
printf("Enterthelengthofreferencestring--");
scanf("%d",&n);
printf("Enterthereferencestring--");
for(i=0;i<n;i++)
{
scanf("%d",&rs[i]);
flag[i]=0;
}
printf("Enterthenumberofframes--");
scanf("%d",&f);
for(i=0;i<f;i++)
{
count[i]=0;
m[i]=-1;
}
printf("\nThePageReplacementprocessis--\n");
for(i=0;i<n;i++)
{
for(j=0;j<f;j++)
{
if(m[j]==rs[i])
{
flag[i]=1;
count[j]=next;
next++;
}
}
if(flag[i]==0)
{
if(i<f)
{
m[i]=rs[i];
count[i]=next;
next++;
}
else
{
min=0;
for(j=1;j<f;j++)
if(count[min]>count[j])
min=j;
Page 46
m[min]=rs[i];
count[min]=next;
next++;
}
pf++;
}
for(j=0;j<f;j++)
printf("%d\t",m[j]);
if(flag[i]==0)
printf("PFNo.--%d",pf);
printf("\n");
}
printf("\nThenumberofpagefaultsusingLRUare%d",pf);
getch();
}

OUTPUT:

Enterthelengthofreferencestring--20
Enterthereferencestring--7
0
1
2
0
3
0
4
2
3
0
3
2
1
2
0
1
7
0
1
Enterthenumberofframes--3

ThePageReplacementprocessis--
7 -1 -1 PFNo.--1
7 0 -1 PFNo.--2
7 0 1 PFNo.--3
2 0 1 PFNo.--4
2 0 1
2 0 3 PFNo.--5
Page 47
2 0 3
4 0 3 PFNo.--6
4 0 2 PFNo.--7
4 3 2 PFNo.--8
0 3 2 PFNo.--9
0 3 2
0 3 2
1 3 2 PFNo.--10
1 3 2
1 0 2 PFNo.--11
1 0 2
1 0 7 PFNo.--12
1 0 7
1 0 7

ThenumberofpagefaultsusingLRUare12

Page 48
LFUPAGEREPLACEMENTALGORITHM

#include<stdio.h>
#include<conio.h>
main()
{
int rs[50],i,j,k,m,f,cntr[20],a[20],min,pf=0;
printf("\nEnternumberofpagereferences--");
scanf("%d",&m);
printf("\nEnterthereferencestring--");
for(i=0;i<m;i++)
scanf("%d",&rs[i]);
printf("\nEntertheavailableno.offrames--");
scanf("%d",&f);
for(i=0;i<f;i++)
{
cntr[i]=0;
a[i]=-1;
}
printf("\nThePageReplacementProcessis–\n");
for(i=0;i<m;i++)
{
for(j=0;j<f;j++)
if(rs[i]==a[j])
{
cntr[j]++;
break;
}
if(j==f)
{
min=0;
for(k=1;k<f;k++)
if(cntr[k]<cntr[min])
min=k;
a[min]=rs[i];
cntr[min]=1;
pf++;
}
printf("\n");
for(j=0;j<f;j++)
printf("\t%d",a[j]);
if(j==f)
printf("\tPFNo.%d",pf);
}
printf("\n\nTotalnumberofpagefaults--%d",pf);
getch();
}

Page 49
OUTPUT:
Enternumberofpagereferences--10

Enterthereferencestring--1
2
3
4
5
2
5
1
4
3

Entertheavailableno.offrames--3

ThePageReplacementProcessis–

1 -1 -1 PFNo.1
1 2 -1 PFNo.2
1 2 3 PFNo.3
4 2 3 PFNo.4
5 2 3 PFNo.5
5 2 3 PFNo.5
5 2 3 PFNo.5
5 2 1 PFNo.6
5 2 4 PFNo.7
5 2 3 PFNo.8

Totalnumberofpagefaults--8

Page 50
EXPERIMENT 10:

AIM: Write a C program to simulate the concept of Dining-Philosophers problem.

DESCRIPTION
The dining-philosophers problem is considered a classic synchronization problem because it is an
example of a large class of concurrency-control problems.It is a simple representation of the need to
allocate several resources among several processes in a deadlock-free and starvation-free manner.
Consider five philosophers who spend their lives thinking and eating. The philosophers share a circular
table surrounded by five chairs, each belonging to one philosopher. In the center table is a bowl of rice,
and the table is laid with five single chop sticks. 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 pickup only one chop stick at a time. Obviously, she cam1otpick 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.

PROBLEM:

int tph,philname[20],status[20],howhung,hu[20],cho;
main()
{
int i;
printf("\n\nDININGPHILOSOPHERPROBLEM");
printf("\nEnterthetotalno.ofphilosophers:");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i]=(i+1);status[i]=1;
}
printf("Howmanyarehungry:");
scanf("%d",&howhung);
if(howhung==tph)
{
printf("\nAllarehungry..\nDeadlockstagewilloccur");printf("\nExiting..");

}
else
{
for(i=0;i<howhung;i++)
{
printf("Enterphilosopher%dposition:",(i+1));
scanf("%d",&hu[i]);
status[hu[i]]=2;
}
do
{
printf("1.Onecaneatatatime\t2.Twocaneatatatime\t3.Exit\nEnteryourchoice:");
scanf("%d",&cho);
switch(cho)
{
Page 51
case 1:one();
break;
case 2:two();
break;
case 3:exit(0);
default:printf("\nInvalidoption..");
}
}while(1);
}
}
one()
{
int pos=0,x,i;
printf("\nAllowonephilosophertoeatatanytime\n");
for(i=0;i<howhung;i++,pos++)
{
printf("\nP%disgrantedtoeat",philname[hu[pos]]);
for(x=pos;x<howhung;x++)
printf("\nP%diswaiting",philname[hu[x]]);
}
}
two()
{
int i,j,s=0,t,r,x;
printf("\nAllowtwophilosopherstoeatatsametime\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%dandP%daregrantedtoeat",philname[hu[i]],philname[hu[j]]);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
printf("\nP%diswaiting",philname[hu[x]]);
}
}
}
}
}

Page 52
OUTPUT:

DININGPHILOSOPHERPROBLEM
Enterthetotalno.ofphilosophers:5
Howmanyarehungry:3
Enterphilosopher1position:2
Enterphilosopher2position:4
Enterphilosopher3position:5
1.Onecaneatatatime 2.Twocaneatatatime 3.Exit
Enteryourchoice:1

Allowonephilosophertoeatatanytime

P3isgrantedtoeat
P3iswaiting
P5iswaiting
P0iswaiting
P5isgrantedtoeat
P5iswaiting
P0iswaiting
P0isgrantedtoeat
P0iswaiting1.Onecaneatatatime 2.Twocaneatatatime 3.Exit
Enteryourchoice:2

Allowtwophilosopherstoeatatsametime

combination1

P3andP5aregrantedtoeat
P0iswaiting

combination2

P3andP0aregrantedtoeat
P5iswaiting

combination3

P5andP0aregrantedtoeat
P3iswaiting1.Onecaneatatatime 2.Twocaneatatatime 3.Exit
Enteryourchoice:3

Page 53
EXPERIMENT 11:

AIM: Write a C program to simulate Bankers algorithm for the purpose of deadlock avoidance and
prevention

DESCRIPTION:
Deadlock avoidance:
In a multi programming environment, several processes may compete for a finite number of resources.
A process requests resources; if there sources are not available at that time, the process enters awaiting
state. Sometimes, awaiting process is never again able to change state, because there sources 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, there sources 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.

Deadlock prevention:
When a new process enters a system, it must declare the maximum number of instances of each
resource type it needed. This number may exceed the total number of resources in the system.
When the user request a set of resources, the system must determine whether the allocation of
each resources will leave the system in safe state. If it will the resources are allocation;
otherwise the process must wait until some other process release the resources.

PROGRAM:

Deadlock avoidance:

#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
};
void main()
{
struct file f[10];
int fl;
int i,j,k,p,b,n,r,g,cnt=0,id,newr;
int avail[10],seq[10];
printf("Enternumberofprocesses--");
scanf("%d",&n);
printf("Enternumberofresources--");
scanf("%d",&r);

Page 54
for(i=0;i<n;i++)
{
printf("EnterdetailsforP%d",i);
printf("\nEnterallocation\t--\t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("EnterMax\t\t--\t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnterAvailableResources\t--\t");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
printf("\nEnterNewRequestDetails--");
printf("\nEnterpid\t--\t");
scanf("%d",&id);
printf("EnterRequestforResources\t--\t");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i]+=newr;
avail[i]=avail[i]-newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
cnt=0;
fl=0;
}
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
Page 55
}
if(b==r)
{
printf("\nP%disvisited",j);
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\nREQUESTNOTGRANTED--DEADLOCKOCCURRED");
printf("\nSYSTEMISINUNSAFESTATE");
goto y;
}
}
printf("\nSYSTEMISINSAFESTATE");
printf("\nTheSafeSequenceis--(");
for(i=0;i<fl;i++)
printf("P%d",seq[i]);
printf(")");
y:printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
getch();
}

Page 56
INPUT
Enternumberofprocess – 5
Enternumberofresourc -- 3
es
EnterdetailsforP0
Enterallocation -- 0 1 0
EnterMax -- 7 5 3

EnterdetailsforP1
Enterallocation -- 2 0 0
EnterMax -- 3 2 2

EnterdetailsforP2
Enterallocation -- 3 0 2
EnterMax -- 9 0 2

EnterdetailsforP3
Enterallocation -- 2 1 1
EnterMax -- 2 2 2

EnterdetailsforP4
Enterallocation -- 0 0 2
EnterMax -- 4 3 3

EnterAvailableResources-- 3 3 2
EnterNewRequestDetails--
Enterpid -- 1
EnterRequestforResources -- 1 0 2

OUTPUT:

P1isvisited(532)
P3isvisited(743)
P4isvisited(745)
P0isvisited(755)
P2isvisited(1057)SYSTEMISI
NSAFESTATE
TheSafeSequenceis --(P1P3P4P0P2)

Process Allocation Max Need

P0 0 1 0 7 5 3 7 4 3
P1 3 0 2 3 2 2 0 2 0
P2 3 0 2 9 0 2 6 0 0
P3 2 1 1 2 2 2 0 1 1
P4 0 0 2 4 3 3 4 3 1

Page 57
DEADLOCK PREVENTION:

#include<stdio.h>
#include<conio.h>
void main()
{
char job[10][10];
int time[10],avail,tem[10],temp[10];
int safe[10];
int ind=1,i,j,q,n,t;
printf("Enternoofjobs:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name and time: ");
scanf("%s%d",&job[i],&time[i]);
}
printf("Enter the available resources:");
scanf("%d",&avail);
for(i=0;i<n;i++)
{
temp[i]=time[i];
tem[i]=i;
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(temp[i]>temp[j])
{
t=temp[i];

temp[i]=temp[j];
temp[j]=t;t=tem[i];
tem[i]=tem[j];tem[j]=t;
}
}
for(i=0;i<n;i++)
{
q=tem[i];
if(time[q]<=avail)
{
safe[ind]=tem[i];
avail=avail-tem[q];
printf("%s",job[safe[ind]]);
ind++;
}
else
{
printf("Nosafesequence\n");
Page 58
}
}
printf("Safesequenceis:");
for(i=1;i<ind;i++)
printf("%s%d\n",job[safe[i]],time[safe[i]]);
getch();
}

OUTPUT:

Enternoofjobs:4
Enter name and time: A1
Enter name and time: B4
Enter name and time: C2
Enter name and time: D3
Enter the available resources:20
ACDBSafesequenceis:A1
C2
D3
B4

Page 59
EXPERIMENT 12:

AIM: Write a c program to implement producer consumer problem using threads

DESCRIPTION:
he Producer-Consumer problem is a classic problem this is used for multi-process synchronization i.e.
synchronization between more than one processes. In the producer-consumer problem, there is
one Producer that is producing something and there is one Consumer that is consuming the products
produced by the Producer.

PROGRAM:

# include <stdio.h>
# include <pthread.h>
# define BufferSize 10
void *Producer();
void *Consumer();
int BufferIndex=0;
char *BUFFER;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t ptid,ctid;
BUFFER=(char *) malloc(sizeof(char) * BufferSize);
pthread_create(&ptid,NULL,Producer,NULL);
pthread_create(&ctid,NULL,Consumer,NULL);
pthread_join(ptid,NULL);
pthread_join(ctid,NULL);
return 0;
}
void *Producer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==BufferSize)
{
pthread_cond_wait(&Buffer_Not_Full,&mVar);
}
BUFFER[BufferIndex++]='@';
printf("Produce : %d \n",BufferIndex);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Empty);
}
}
void *Consumer()
{
Page 60
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==-1)
{
pthread_cond_wait(&Buffer_Not_Empty,&mVar);
}
printf("Consume : %d \n",BufferIndex--);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Full);
}
}

OUTPUT:

Produce : 1
Produce : 2
Produce : 3
Produce : 4
Produce : 5
Produce : 6
Produce : 7
Produce : 8
Produce : 9
Produce : 10
Consume : 10
Consume : 9
Consume : 8
Consume : 7
Consume : 6
Consume : 5
Consume : 4
Consume : 3
Consume : 2
Consume : 1
Consume : 0
Produce : 0
Produce : 1
Produce : 2
Produce : 3
Produce : 4
Produce : 5
Produce : 6
Produce : 7
Produce : 8
Produce : 9
Produce : 10
Consume : 10
Consume : 9
Page 61
Consume : 8
Consume : 7
Consume : 6
Consume : 5
Consume : 4
Consume : 3
Consume : 2
Consume : 1
Consume : 0

Page 62
EXPERIMENT 13:

AIM: Write a c program to implement sleeping barber problem.

DESCRIPTION:
The analogy is based upon a hypothetical barber shop with one barber. The barber has one barber's chair
in a cutting room and a waiting room containing a number of chairs in it. When the barber finishes cutting
a customer's hair, he dismisses the customer and goes to the waiting room to see if there are others
waiting. If there are, he brings one of them back to the chair and cuts their hair. If there are none, he
returns to the chair and sleeps in it.Each customer, when they arrive, looks to see what the barber is doing.
If the barber is sleeping, the customer wakes him up and sits in the cutting room chair. If the barber is
cutting hair, the customer stays in the waiting room. If there is a free chair in the waiting room, the
customer sits in it and waits their turn. If there is no free chair, the customer leaves.

PROGRAM:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_CUSTOMERS 25
void *customer(void *num);
void *barber(void *);
void randwait(int secs);
sem_t waitingRoom;
sem_t barberChair;
sem_t barberPillow;
sem_t seatBelt;
int allDone = 0;
int main(int argc, char *argv[]) {
pthread_t btid;
pthread_t tid[MAX_CUSTOMERS];
long RandSeed;
int i, numCustomers, numChairs;
int Number[MAX_CUSTOMERS];
printf("Enter the number of Custmors : ");
scanf("%d",&numCustomers) ;
printf("Enter the number of Charis : ");
scanf("%d",&numChairs);
if (numCustomers > MAX_CUSTOMERS) {
printf("The maximum number of Customers is %d.\n", MAX_CUSTOMERS);
exit(-1);
}
for (i=0; i<MAX_CUSTOMERS; i++)
{
Number[i] = i;

Page 63
}
sem_init(&waitingRoom, 0, numChairs);
sem_init(&barberChair, 0, 1);
sem_init(&barberPillow, 0, 0);
sem_init(&seatBelt, 0, 0);
pthread_create(&btid, NULL, barber, NULL);
for (i=0; i<numCustomers; i++)
{
pthread_create(&tid[i], NULL, customer, (void *)&Number[i]);
sleep(1);
}
for (i=0; i<numCustomers; i++) {
pthread_join(tid[i],NULL);
sleep(1);
}
allDone = 1;
sem_post(&barberPillow);
pthread_join(btid,NULL);
}
void *customer(void *number)
{
int num = *(int *)number;
printf("Customer %d leaving for barber shop.\n", num);
randwait(2);
printf("Customer %d arrived at barber shop.\n", num);
sem_wait(&waitingRoom);
printf("Customer %d entering waiting room.\n", num);
sem_wait(&barberChair);
sem_post(&waitingRoom);
printf("Customer %d waking the barber.\n", num);
sem_post(&barberPillow);
sem_wait(&seatBelt);
sem_post(&barberChair);
printf("Customer %d leaving barber shop.\n", num);
}
void *barber(void *junk)
{
while (!allDone)
{
printf("The barber is sleeping\n");
sem_wait(&barberPillow);
if (!allDone) {
printf("The barber is cutting hair\n");
randwait(2);
printf("The barber has finished cutting hair.\n");
sem_post(&seatBelt);
}
else
{
Page 64
printf("The barber is going home for the day.\n");
}
}
}
void randwait(int secs)
{
int len;
len = (int) ((1 * secs) + 1);
sleep(len);
}

INPUT:

Enter the number of Custmors : 1


Enter the number of Charis : 1

OUTPUT:

Customer 0 leaving for barber shop.


The barber is sleeping
Customer 0 arrived at barber shop.
Customer 0 entering waiting room.
Customer 0 waking the barber.
The barber is cutting hair
The barber has finished cutting hair.
The barber is sleeping
Customer 0 leaving barber shop.
The barber is going home for the day

Page 65

You might also like