os lab manual 2022
os lab manual 2022
Lab Manual
Week-2
fact=1
echo $fact
output
bash fact
b)
#!bin/bash
h=$(date +"%H")
if [ $h -gt 6 -a $h -le 12 ]
then
echo good morning
elif [ $h -gt 12 -a $h -le 16 ]
then
echo good afternoon
elif [ $h -gt 16 -a $h -le 20 ]
then
echo good evening
else
echo good night
fi
ooutput
create a file with shell extention(filename.sh)
Week-3
#include<sys/types.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[3])
{
int fd,i;
char buf[2];
fd=open(argv[1],O_RDONLY,0777);
if(fd==-argc)
{
printf("file open error");
}
else
{
printf("your program is printing data in the file \n");
while(i=read(fd,buf,1)>0)
{
printf("%c",buf[0]);
}
close(fd);
}
}
output
gcc week3.c
./a.out fact.c
week 4
a.) cp command
Exp 4: copy command
#include <stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include <string.h>
#define BUF_SIZE 32
#define FILE_NAME_LEN 200
int main(int argc, char *argv[])
{
FILE * file_to_read;
FILE * file_to_write;
char name_of_file_to_read[FILE_NAME_LEN+1];
char name_of_file_to_write[FILE_NAME_LEN+1];
char buf[BUF_SIZE];
size_t num_rec;
if(argc>3 || argc<3)
{
printf("Please Provide two arugments \n");
}
else{
if(access(argv[1],F_OK)<0)
{
printf("%s not found \n ",argv[1]);
}
/* Prepare the source file name */
strcpy(name_of_file_to_read, argv[1]);
/* Prepare the target file name */
if ( argc == 3 )
strcpy(name_of_file_to_write, argv[2]);
else
strcat(strcpy(name_of_file_to_write, name_of_file_to_read), ".fread");
/* Open source file in read-only mode */
if ( (file_to_read = fopen(name_of_file_to_read, "r")) == NULL )
{
fprintf(stderr, "Could not open file '%s' for reading\n",name_of_file_to_read);
return 3;
}
/* Open target file in write mode */
if ( (file_to_write = fopen(name_of_file_to_write, "w")) == NULL )
{
fprintf(stderr, "Could not open file '%s' for writing\n",
name_of_file_to_write);
fclose(file_to_read);
return 4;
}
while ( (num_rec = fread(buf, sizeof(char), BUF_SIZE, file_to_read) ) > 0 )
{
fwrite(buf, sizeof(char), num_rec, file_to_write);
if ( ferror(file_to_write) )
{
fprintf(stderr, "Error while writing into file '%s'\n",
name_of_file_to_write);
fclose(file_to_read);
fclose(file_to_write);
return 5;
}
}
if ( ferror(file_to_read) )
{
fprintf(stderr, "Error while reading the file '%s'\n", name_of_file_to_read);
fclose(file_to_read);
fclose(file_to_write);
return 6;
}
/* Close the files */
fclose(file_to_read);
fclose(file_to_write);
printf("File '%s' successfully copied to file '%s'\n", name_of_file_to_read,
name_of_file_to_write);
return 1;
}
}
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main(int argc,char *argv[])
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}
Output:
[latha@localhost ~]$ cc week11c
[latha@localhost ~]$ ./a.out vowl2 ex
file1=vowl2 file2=ex
[latha@localhost ~]$ cat vowl2
cat: vowl2: No such file or directory
[latha@localhost ~]$ cat ex
apple
ball
ghj
latha bhavya REVATHI
CMRIT CMRCET CMREC CMRTC
week 5
C program to create a child process and allow the parent to display “parent” and the
child to display “child” on the screen
#include <stdio.h>
#include<stdlib.h>
int main(void)
int pid;
int status;
printf("Hello World!\n");
pid = fork( );
perror("bad fork");
exit(1);
if (pid == 0)
int main() {
int pipefds1[2], pipefds2[2];
int returnstatus1, returnstatus2;
int pid;
char pipe1writemessage[20] = "Hi";
char pipe2writemessage[20] = "Hello";
char readmessage[20];
returnstatus1 = pipe(pipefds1);
if (returnstatus1 == -1) {
printf("Unable to create pipe 1 \n");
return 1;
}
returnstatus2 = pipe(pipefds2);
if (returnstatus2 == -1) {
printf("Unable to create pipe 2 \n");
return 1;
}
pid = fork();
if (pid != 0)
{
close(pipefds1[0]);
close(pipefds2[1]);
printf("In Parent: Writing to pipe 1 – Message is %s\n", pipe1writemessage);
gcc week6.c
./a.out
CPU Utilization: This is the percentage of time that the processor is busy. CPU utilization
may range from 0 to 100
First-come, first-serve scheduling(FCFS): In this, which process enter the ready queue first
is served first. The OS maintains DS that is ready queue. It is the simplest CPU scheduling
algorithm. If a process request the CPU then it is loaded into the ready queue, which process
is the head of the ready queue, connect the CPU to that process.
Shortest job First: The criteria of this algorithm are which process having the smallest CPU
burst, CPU is assigned to that next process. If two process having the same CPU burst time
FCFS is used to break the tie.
Priority Scheduling: These are of two types.
One is internal priority, second is external priority. The cpu is allocated to the process with
the highest priority. Equal priority processes are scheduled in the FCFS order. Priorities are
generally some fixed range of numbers such as 0 to 409. The low numbers represent high
priority
Round Robin: It is a primitive scheduling algorithm it is designed especially for time sharing
systems. In this, the CPU switches between the processes. When the time quantum expired,
the CPU switches to another job. A small unit of time called a quantum or time slice. A time
quantum is generally is a circular queue new processes are added to the tail of the ready
queue.
If the process may have a CPU burst of less than one time slice then the
process release the CPU voluntarily. The scheduler will then process to next process ready
queue otherwise; the process will be put at the tail of the ready queue.
A)FCFS ALGORITHM:
int pid[10],bt[10],wt[10],tat[10],n,twt=0,ttat=0,i;
float awt,atat;
clrscr();
printf("Enter no.of processes:");
scanf("%d",&n);
printf("\n Enter burst times:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
wt[0]=0;
tat[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=tat[i-1];
tat[i]=bt[i]+wt[i];
}
for(i=0;i<n;i++)
{
ttat= ttat+tat[i];
twt=twt+wt[i];
}
printf("\n PID \t BT \t WT \t TAT");
for(i=0;i<n;i++)
printf("\n %d\t%d\t%d\t%d",i+1,bt[i],wt[i],tat[i]);
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\nAvg. Waiting Time=%f",awt);
printf("\nAvg. Turn around time=%f",atat);
getch();
}
OUTPUT:
B)PRIORITY ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id, process priority and accept the
CPU burst time
Step 4: Start the Ready Q according the highest priority by sorting according to highest to
lowest priority.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
Step 6: For each process in the ready queue, calculate
(a) Waiting time for process(n)= waiting time of process (n-1)+Burst time of process(n-1)
(b) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(c) Average waiting time = Total waiting Time / Number of process
(d) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int pid[10],bt[10],pr[10],wt[10],tat[10],n,twt=0,ttat=0,i,j,t;
float awt,atat;
clrscr();
printf("Enter no.of processes:");
scanf("%d",&n);
printf("\n Enter burst times:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
t=bt[i];
bt[i]=bt[j];
bt[j]=t;
t=pid[i];
pid[i]=pid[j];
pid[j]=t;
}
}
}
wt[0]=0;
tat[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=tat[i-1];
tat[i]=bt[i]+wt[i];
}
for(i=0;i<n;i++)
{
ttat= ttat+tat[i];
twt=twt+wt[i];
}
printf("\n PID PRIORITY \t BT \t WT \t TAT");
for(i=0;i<n;i++)
printf("\n %d\t%d\t%d\t%d\t%d",pid[i],pr[i],bt[i],wt[i],tat[i]);
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\nAvg. Waiting Time=%f",awt);
printf("\nAvg. Turn around time=%f",atat);
getch();
}
OUTPUT:
VIVA-VOCE:
1.What is an Operating system?
An operating system (OS) is system software that manages computer hardware and software
resources and provides common services for computer programs.
2.What is a process ?
A process is an instance of program in execution. The operating system is responsible for
managing all the processes that are running on a computer and allocated each process a
certain amount of time to use the processor.
3. What Are The Advantages Of A Multiprocessor System?
With an increased number of processors, there is considerable increase in throughput. It can also save
more money because they can share resources. Finally, overall reliability is increased as well.
Starvation or indefinite blocking is phenomenon associated with the Priority scheduling algorithms, in
which a process ready to run for CPU can wait indefinitely because of low priority.
Aging is a technique of gradually increasing the priority of processes that wait in the system for a
long time.
5.What are the functions of operating system?
The operating system controls and coordinates the use of hardware among the different processes and
applications. It provides the various functionalities to the users. The following are the main job of
operating system.
- Resource utilization
- Resource allocation
- Process management
- Memory management
- File management
- I/O management
- Device management
6.What do you know about interrupt?
Interrupt can be understood as a signal from a device causing context switch.
- To handle the interrupts, interrupt handlers or service routines are required.
- The address of each Interrupt service routine is provided in a list which is maintained in interrupt
vector.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main(){
int pid[10],bt[10],wt[10],tat[10],n,twt=0,ttat=0,i,j,t;
float awt,atat;
clrscr();
printf("Enter no.of processes:");
scanf("%d",&n);
printf("\n Enter burst times:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
printf("\n Enter PID:");
for(i=0;i<n;i++)
scanf("%d",&pid[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(bt[i]>bt[j])
{
t=bt[i];
bt[i]=bt[j];
bt[j]=t;
t=pid[i];
pid[i]=pid[j];
pid[j]=t;
}
}
}
wt[0]=0;
tat[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=tat[i-1];
tat[i]=bt[i]+wt[i];
}
for(i=0;i<n;i++)
{
ttat= ttat+tat[i];
twt=twt+wt[i];
}
printf("\n PID \t BT \t WT \t TAT");
for(i=0;i<n;i++)
printf("\n %d\t%d\t%d\t%d",pid[i],bt[i],wt[i],tat[i]);
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\nAvg. Waiting Time=%f",awt);
printf("\nAvg. Turn around time=%f",atat);
getch();
}
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int ts,bt1[10],wt[10],tat[10],i,j=0,n,bt[10],ttat=0,twt=0,tot=0;
float awt,atat;
clrscr();
printf("Enter the number of Processes \n");
scanf("%d",&n);
{
wt[i]=tat[i]-bt1[i];
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n PID \t BT \t WT \t TAT\n");
for(i=1;i<=n;i++) {
printf("\n %d \t %d \t %d \t %d \t\n",i,bt1[i],wt[i],tat[i]);
}
printf("\n The average Waiting Time=%f",awt);
printf("\n The average Turn around Time=%f",atat);
getch();
}
OUTPUT:
for(j=0;j<b[i];j++)
c[i][j]=sb[i]++;
}
printf("Filename\tStart block\tlength\n");
for(i=0;i<n;i++)
printf("%d\t\t %d \t\t%d\n",i+1,t[i],b[i]);
printf("Enter file name:");
scanf("%d",&x);
printf("\nFile name is:%d",x);
printf("\nlength is:%d",b[x-1]);
printf("\nblocks occupied:");
for(i=0;i<b[x-1];i++)
printf("%4d",c[x-1][i]);
getch();
OUTPUT:
b) Linked
In the chained method file allocation table contains a field which points to starting block of
memory. From it for each bloc a pointer is kept to next successive block. Hence, there is no
external fragmentation.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly q= random(100);
a) Check whether the selected location is free .
b) If the location is free allocate and set flag=1 to the allocated locations.
q=random(100);
{
if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
Step 5: Print the results file no, length ,Blocks allocated.
Step 6: Stop the program
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
main()
{
int i,j,n;
//clrscr();
printf("\t\t Linked File allocation algorithm");
printf("\nEnter 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=0;j<f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d\n",f[i].block[j]);
}
getch();
}
OUTPUT:
Enter no. of files:3
Enter file name:1
Enter starting block:50
Enter no.of blocks:5
Enter block numbers:10
20
60
70
Enter file name:1
Enter starting block:21
Enter no.of blocks:3
Enter block numbers:101
201
Enter file name:3
Enter starting block:31
Enter no.of blocks:3
Enter block numbers:234
456
File start size block
1 50 5 50--->10--->20--->60--->70
1 21 3 21--->101--->201
3 31 3 31--->234---> 456
c) Indexed
In the chained method file allocation table contains a field which points to starting block of
memory. From it for each bloc a pointer is kept to next successive block. Hence, there is no
external fragmentation
ALGORTHIM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly
q= random(100);
a) Check whether the selected location is free .
b) If the location is free allocate and set flag=1 to the allocated locations.
While allocating next location address to attach it to previous location
for(i=0;i0)
{}
}
p=r[i][j-1];
b[p].next=q;
}
Step 5: Print the results file no, length ,Blocks allocated.
Step 6: Stop the program
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
main()
{
int n,m[20],i,j,sb[20],b[20][20],x;
//clrscr();
printf("\t\t Indexed File allocation algorithm");
printf("\nEnter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter index block of file%d:",i+1);
scanf("%d",&sb[i]);
printf("\nEnter length of file%d:",i+1);
scanf("%d",&m[i]);
printf("enter blocks 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]);
}
printf("\nEnter file name:");
scanf("%d",&x);
printf("\nfile name is:%d",x);
printf("\nIndex is:%d",sb[x-1]);
printf("\nBlocks occupied are:");
for(j=0;j<m[x-1];j++)
printf("%4d",b[x-1][j]);
getch();
}
OUTPUT:
Enter no. of files:3
Enter file name:A
Enter starting block:10
Enter no.of blocks:5
Enter block numbers:10
44
12
34
Enter file name:B
Enter starting block:50
Enter no.of blocks:3
Enter block numbers:21
23
Enter file name:10
Enter starting block:20
Enter no.of blocks:5
Enter block numbers:56
65
43
32
File start size block
A 10 5 10--->10--->44--->12--->34
B 50 3 50--->21--->23
10 20 5 20--->56--->65--->43--->32
VIVA-VOCE:
1.Explain file allocation in Operating system?
A file allocation table (FAT) is a table that an operating system maintains on a hard disk
that provides a map of the clusters (the basic units of logical storage on a hard disk) that
a file has been stored in.
2.What is contiguous and noncontiguous memory allocations?
The basic difference between contiguous and noncontiguous memory allocationis
that contiguous allocation allocates one single contiguous block of memory to the process
whereas, the noncontiguous allocation divides the process into several blocks and place
them in the different address space of the memory.
3. Explain Sequential allocation?
In this scheme, each file occupies a contiguous set of blocks on the disk. For example, if
a file requires n blocks and is given a block b as the starting location, then the blocks
assigned to the file will be: b, b+1, b+2,……b+n-1. This means that given the starting block
address and the length of the file (in terms of blocks required.The directory entry for a file
with contiguous allocation contains
Address of starting block
Length of the allocated portion.
Advantages of FAT:The main advantage of FAT is its efficient use of disk space. FAT can
place the parts of the file wherever they fit. File names can be up to 255 characters and file
extensions longer than 3 characters. Easy to recover file names that have been deleted.
Disadvantages of FAT:Overall performance slows down as more files are stored on the
drive. Drives can become fragmented quite easily. FAT lacks many of the security features in
NTFS such as being able to assign access rights to files and directories. It can also have file
integrity problems such as lost clusters, invalid files and directories and allocation errors.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,temp,framearr[20],pages,pageno,frames,memsize,log,pagesize,prosize,base;
clrscr();
printf("Enter the Process size: ");
scanf("%d",&prosize);
printf("\nEnter the main memory size: ");
scanf("%d",&memsize);
printf("\nEnter the page size: ");
scanf("%d",&pagesize);
pages=prosize/pagesize;
printf("\nThe process is divided into %d pages",pages);
frames = memsize/pagesize;
printf("\n\nThe main memory is divided into %d frames\n",frames);
for(i=0;i<frames;i++)
framearr[i]=-1; /* Initializing array elements with -1*/
for(i=0;i<pages;i++)
{
pos: printf("\nEnter the frame number of page %d: ",i);
scanf("%d",&temp); /* storing frameno in temporary variable*/
if(temp>=frames) /*checking wether frameno is valid or not*/
{
printf("\n\t****Invalid frame number****\n");
goto pos;
}
/* storing pageno (i.e 'i' ) in framearr at framno (i.e temp ) index */
for(j=0;j<frames;j++)
if(temp==j)
framearr[temp]=i;
}
printf("\n\nFrameno\tpageno\tValidationBit\n------\t------\t----------");
for(i=0;i<frames;i++)
{
printf("\n %d \t %2d \t",i,framearr[i]);
if(framearr[i]==-1)
printf(" 0");
else
printf(" 1");
}
printf("\nEnter the logical address: ");
scanf("%d",&log);
printf("\nEnter the base address: ");
scanf("%d",&base);
pageno = log/pagesize;
for(i=0;i<frames;i++)
if(framearr[i]==pageno)
{
temp = i;
break;
}
j = log%pagesize; /* here 'j' is displacement */
temp = base + (temp*pagesize)+j; /* here lhs 'temp' is physical address and rhs
'temp' is frame number */
printf("\nPhysical address is : %d",temp);
getch();
}
OUTPUT:
b) Segmentation
Theory: A process is divided into Segments. The chunks that a program is divided into
which are not necessarily all of the same sizes are called segments. Segmentation gives
user’s view of the process which paging does not give. Here the user’s view is mapped to
physical memory.
Algorithm:
1. Input the number of memory blocks and their sizes and initializes all the blocks as
free.
2. Input the number of processes and their sizes.
3. Start by picking each process and check if it can be assigned to the current block, if
yes, allocate it the required memory and check for next process but from the block where we
left not from starting.
4. If the current block size is smaller then keep checking the further blocks.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,m,size,val[10][10],badd[20],limit[20],ladd;
//clrscr();
printf("\n \t\tSegmentation");
printf("\n Enter the size of the segment table:");
scanf("%d",&size);
for(i=0;i<size;i++)
{
printf("\nEnter infor about segment %d",i+1);
printf("\nEnter base address:");
scanf("%d",&badd[i]);
printf("\nEnter the limit:");
scanf("%d",&limit[i]);
for(j=0;j<limit[i];j++)
{
printf("\nEnter %d address values:",badd[i]+j);
scanf("%d",&val[i][j]);
}
}
printf("\n\n****SEGMENT TABLE****");
printf("\nseg.no\tbase\tlimit\n");
for(i=0;i<size;i++)
{
printf("%d\t%d\t%d\n",i+1,badd[i],limit[i]);
}
printf("\nEnter segment no.::");
scanf("%d",&i);
if(i>=size)
{
printf("invalid");
}
else
{
printf("\nEnter the logical address:");
scanf("%d",&ladd);
if(ladd>=limit[i])
printf("invalid");
else
{
m=badd[i]+ladd;
printf("\nmapped physical address is=%d",m);
printf("\nthe value is %d ",val[i][ladd]);
}
}
getch();
}
OUTPUT:
Enter segment number:1
Enter base value:2000
Enter value for limit:100
Enter segment number:2
Enter base value:2500
Enter value for limit:100
Enter segmentation number:-1
Enter offset:90
Enter segment number:2
Address in physical memory 2590
VIVA-VOCE:
1. What is the basic function of paging?
Paging is a memory management scheme that permits the physical address space of a process to be
noncontiguous. It avoids the considerable problem of having to fit varied sized memory chunks onto
the backing store.
2.What is fragmentation?
Fragmentation is memory wasted. It can be internal if we are dealing with systems that have fixed-
sized allocation units, or external if we are dealing with systems that have variable-sized allocation
units.
3.What is Thrashing?
Thrashing is a situation when the performance of a computer degrades or collapses.
Thrashing occurs when a system spends more time processing page faults than executing
transactions.
- Physical addresses are actual addresses used for fetching and storing data in main memory when the
process is under execution.
- Logical addresses are generated by user programs. During process loading, they are converted
by the loader into physical address.
5. Explain compaction.
During the process of loading and removal of process into and out of the memory, the free
memory gets broken into smaller pieces. These pieces lie scattered in the memory.
Compaction means movement of these pieces close to each other to form a larger chunk of
memory which works as a resource to run larger processes.
6.Explain Internal fragmentation and external fragmentation?
Internal fragmentation is the wasted space within each allocated block because of rounding
up from the actual requested allocation to the allocation granularity.
External fragmentation is the various free spaced holes that are generated in either memory
or disk space.
THEORY:Deadlock:
A process request the resources, the resources are not available at that time, so the
process enter into the waiting state. The requesting resources are held by another waiting
process, both are in waiting state, this situation is said to be Deadlock.
A deadlocked system must satisfied the following 4 conditions. These are:
(i) Mutual Exclusion: Mutual Exclusion means resources are in non-sharable mode only, it
means only one process at a time can use a process.
(ii) Hold and Wait: Each and every process is the deadlock state, must holding at least one
resource and is waiting for additional resources, that are currently being held by another
process.
(iii) No Preemption: No Preemption means resources are not released in the middle of the
work, they released only after the process has completed its task.
(iv) Circular Wait: If process P1 is waiting for a resource R1, it is held by P2, process P2 is
waiting for R2, R2 held by P3, P3 is waiting for R4, R4 is held by P2, P2 waiting for resource
R3, it is held by P1.
P1 R1 P2 R2 P3 R4 P2 R3
Deadlock Avoidance: It is one of the method of dynamically escaping from the deadlocks. In
this scheme, if a process request for resources, the avoidance algorithm checks before the
allocation of resources about the state of system. If the state is safe, the system allocate the
resources to the requesting process otherwise (unsafe) do not allocate the resources. So taking
care before the allocation said to be deadlock avoidance.
Banker’s Algorithm: It is the deadlock avoidance algorithm, the name was chosen because
the bank never allocates more than the available cash.
Available: A vector of length ‘m’ indicates the number of available resources of each type. If
available[j]=k, there are ‘k’ instances of resource types Rj available.
Allocation: An nxm matrix defines the number of resources of each type currently allocated
to each process. If allocation[i,j]=k, then process Pi is currently allocated ‘k’ instances of
resources type Rj.
Max: An nxm matrix defines the maximum demand of each process. If max[i,j]=k, then Pi
may request at most ‘k’ instances of resource type Rj.
Need: An nxm matrix indicates the remaining resources need of each process. If need[I,j]=k,
then Pi may need ‘k’ more instances of resource type Rj to complete this task. There fore,
Need[i,j]=Max[i,j]-Allocation[I,j]
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both Finish[i] =False Need<=Work
If no such I exists go to step 4.
3. work=work+Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
Resource request algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi wants k
instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.
3. Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows;
Available=Available-Request I;
Allocation I =Allocation+Request I; Need i=Need i-Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request i and the
old resource-allocation state is restored.
ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether it’s possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. Or not if we allow the request.
10. Stop the program.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
int k,rq[10],i,j,count,temp=0,R[10],n,r,max[10][10], alloc[10][10],need[10]
[10],tr[10],p,q,avail[10],availb[10][10],availa[10][10];
void main()
{clrscr();
printf("enter no of process:");
scanf("%d",&n);
printf("\nenter no of resources:");
scanf("%d",&r);
for(i=1;i<=n;i++)
{
printf("process %d",i);
for(j=1;j<=r;j++)
{
printf("maximum value of resource:%d",i);
scanf("%d",&max[i][j]);
}
for(j=1;j<=r;j++)
{
printf("allocated from resource %d:",i);
scanf("%d",&alloc[i][j]);
}
}
for(i=1;i<=r;i++)
{
printf("enter total value of resource %d",i);
scanf("%d",&tr[i]);
}for(i=1;i<=n;i++)
{
for(j=1;j<=r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}}
printf("\nresources\tallocated\tneeded\n");
for(i=1;i<=n;i++)
{printf("p%d\t",i);
for(j=1;j<=r;j++)
{printf("%d",max[i][j]);
}printf("\t");
for(j=1;j<=r;j++)
{printf("%d",alloc[i][j]);
}
printf("\t");
for(j=1;j<=r;j++)
{
printf("%d",need[i][j]);
}printf("\n");
}
R[1]=0;
for(j=1;j<=r;j++)
{
for (i=1;i<=n;i++)
{ R[j]=R[j]+alloc[i][j];
}
avail[j]=tr[j]-R[j];
}
printf("total\t avail\n");
for(i=1;i<=r;i++)
{
printf("%d",tr[i]);
} printf("\t");
for(i=1;i<=r;i++)
{
printf("%d",avail[i]);
}
for(i=1;i<=n;i++)
{ count=0;
for(j=1;j<=r;j++)
{
if(avail[j]>=need[i][j])
{count=count+1;
if(count==r)
{
printf("the above sequence is a safe sequence");
q=i,p=i;
goto pos;
}
}
}temp=temp+1;
}
if(temp==n)
{
printf("\ndead lock");
exit();
}
pos:printf("\n\tavailb\tavaila\n");
printf("p%d\t",p);
for(i=1;i<=r;i++)
{
availb[p][i]=avail[i]-need[p][i];
printf("%d",availb[p][i]);
} printf("\t");
for(i=1;i<=r;i++)
{
availa[p][i]=max[p][i]+availb[p][i];
printf("%d",availa[p][i]);
}
printf("\n");
for(i=1;i<=n;i++)
{
if(i!=q)
{printf("p%d\t",i);
for(j=1;j<=r;j++)
{
availb[i][j]=availa[p][j]-need[i][j];
printf("%d",availb[i][j]);
}printf("\t");
for(j=1;j<=r;j++)
{
availa[i][j]=availb[i][j]+max[i][j];
printf("%d",availa[i][j]);
}
p=i;
printf("\n");
}
}
printf("enter the process to be requested");
scanf("%d",&k);
printf("\nenter the request value");
for(i=1;i<=r;i++)
{
scanf("%d",&rq[i]);
}
count=0;
for(i=1;i<=r;i++)
{
if(need[k][i]>=rq[i]&&avail[i]>=rq[i])
{
count=count+1;
if(count==r)
{
for(i=1;i<=r;i++)
{
avail[i]=avail[i]-rq[i];
}
}
}
}temp=0;
for(i=1;i<=n;i++)
{
count=0;
if(i!=k)
{
for(j=1;j<=r;j++)
{
if(need[i][j]>=avail[j])
{
count=count+1;
if(count==r)
{
printf("request granted\n");
exit();
}
}
}
}
temp=temp+1;
}
if(temp==n)
{
printf("request rejected");
exit();
}
getch();
}
OUTPUT:
VIVA-VOCE:
1.What is deadlock?
Deadlock is a situation when two or more processes wait for each other to finish and none of them
ever finish. Consider an example when two trains are coming toward each other on same track and
there is only one track, none of the trains can move once they are in front of each other. Similar
situation occurs in operating systems when there are two or more processes hold some resources and
wait for resources held by other(s).
printf("\n FIFO Page Replacement Algorithm\n\n The given reference string is:\n\n");
for(i=0;i<n;i++)
{
printf(" %d ",a[i]);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("\nReference No %d-> ",a[i]);
avail=0;
for(k=0;k<fno;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j = (j+1) % fno;
pagefault++;
for(k=0;k<fno;k++)
if(frame[k]!=-1)
printf(" %2d",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d",pagefault);
}
OUTPUT:
B) LRU Algorithm:
1. Start
2. Read the number of frames
3. Read the number of pages
4. Read the page numbers
5. Initialize the values in frames to -1
6. Allocate the pages in to frames by selecting the page that has not been used for the longest
period of time.
7. Display the number of page faults.
8. Stop
SOURCE CODE:
#include<stdio.h>
void main()
{
int i,j,l,max,n,a[50],frame[10],flag,fno,k,avail,pagefault=0,lru[10];
printf("\nEnter the number of Frames : ");
scanf("%d",&fno);
printf("\nEnter number of reference string :");
scanf("%d",&n);
printf("\n Enter the Reference string :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<fno;i++)
{
frame[i]= -1;
lru[i] = 0;
}
printf("\nLRU Page Replacement Algorithm\n\nThe given reference string is:\n\n");
for(i=0;i<n;i++)
{
printf(" %d ",a[i]);
}
printf("\n");
j=0;
for(i=0;i<n;i++)
{
max = 0;
flag=0;
printf("\nReference No %d-> ",a[i]);
avail=0;
for(k=0;k<fno;k++)
if(frame[k]==a[i])
{
avail=1;
lru[k]=0;
break;
}
if(avail==1)
{
for(k=0;k<fno;k++)
if(frame[k]!=-1)
++lru[k];
max = 0;
for(k=1;k<fno;k++)
if(lru[k]>lru[max])
max = k;
j = max;
}
if(avail==0)
{
lru[j]=0;
frame[j]=a[i];
for(k=0;k<fno;k++)
{
if(frame[k]!=-1)
++lru[k];
else
{
j = k;
flag = 1;
break;
}
}
if(flag==0){
max = 0;
for(k=1;k<fno;k++)
if(lru[k]>lru[max])
max = k;
j = max;
}
pagefault++;
for(k=0;k<fno;k++)
if(frame[k]!=-1)
printf(" %2d",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d",pagefault);
}
OUTPUT:
C) Optimal Algorithm:
1. Start
2. Read the number of frames
3. Read the number of pages
4. Read the page numbers
5. Initialize the values in frames to -1
6. Allocate the pages in to frames by selecting the page that will not be used for the longest
period of time.
7. Display the number of page faults.
8. Stop
SOURCE CODE:
#include<stdio.h>
int main()
{
int i,j,l,min,flag1,n,a[50],temp,frame[10],flag,fno,k,avail,pagefault=0,opt[10];
printf("\nEnter the number of Frames : ");
scanf("%d",&fno);
printf("\nEnter number of reference string :");
scanf("%d",&n);
printf("\n Enter the Reference string :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<fno;i++)
{
frame[i]= -1;
opt[i]=0;
}
printf("\n Optimal Page Replacement Algorithm\n\nThe given reference string is:\n\n");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
j=0;
for(i=0;i<n;i++)
{
flag=0;
flag1=0;
printf("\nReference No %d-> ",a[i]);
avail=0;
for(k=0;k<fno;k++)
if(frame[k]==a[i])
{
avail=1;
break;
}
if(avail==0)
{
temp = frame[j];
frame[j]=a[i];
for(k=0;k<fno;k++)
{
if(frame[k]==-1)
{
j = k;
flag = 1;
break;
}
}
if(flag==0)
{
for(k=0;k<fno;k++)
{
opt[k]=0;
for(l=i;l<n;l++)
{
if(frame[k]==a[l])
{
flag1 = 1;
break;
}
}
if(flag1==1)
opt[k] = l-i;
else
{
opt[k] = -1;
break;
}
}
min = 0;
for(k=0;k<fno;k++)
if(opt[k]<opt[min]&&opt[k]!=-1)
min = k;
else if(opt[k]==-1)
{
min = k;
frame[j] = temp;
frame[k] = a[i];
break;
}
j = min;
}
pagefault++;
for(k=0;k<fno;k++)
if(frame[k]!=-1)
printf(" %2d",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d",pagefault);
return 0;
}
OUTPUT:
VIVA-VOCE:
1.What is a page fault?
A page fault occurs when a program attempts to access data or code that is in its address
space, but is not currently located in the system RAM.
2.Why do we use page replacement algorithms?
Whenever a new page is referred and not present in memory, page fault occurs and
Operating System replaces one of the existing pages with newly needed page.
3.Explain virtual memory?
Virtual memory is a memory management capability of an OS that uses hardware and
software to allow a computer to compensate for physical memory shortages by temporarily
transferring data from random access memory (RAM) to disk storage. Virtual address space
is increased using active memory in RAM and inactive memory in hard disk drives (HDDs)
to form contiguous addresses that hold both the application and its data.
4.Explain LRU with example.
Consider the following reference string as an example for better understanding of the LRU
algorithm.