Os Lab Manual
Os Lab Manual
Faculty Incharge
Program No: 1
TITLE: Simulation of the CPU scheduling algorithm
Non-Preemptive FCFS
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
FCFS: With this scheme, the process that requests the CPU first is allocated the CPU
first. The implementation of the FCFS policy is easily managed with a FIFO queue.
1.3CODING:
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fflush(stdin);
printf("\n\n Enter the process name: ");
scanf("%s",&pname[i]);
printf("\n Enter The BurstTime for Process %s =",pname[i]);
scanf("%d",&Bu[i]);
printf("\n Enter the Arrival Time for Process %s =",pname[i]);
scanf("%d",&A[i]);
}
}
//DISPLAYING THE GANTT CHART
void Gantt_chart()
{
int i;
printf("\n\n\t\t\tGANTT CHART\n");
printf("\n-----------------------------------------------------------\n");
for(i=1;i<=n;i++)
printf("|\t%s\t",pname[i]);
printf("|\t\n");
printf("\n-----------------------------------------------------------\n");
printf("\n");
for(i=1;i<=n;i++)
printf("%d\t\t",Wt[i]);
printf("%d",Wt[n]+Bu[n]);
printf("\n-----------------------------------------------------------\n");
printf("\n");
}
//CALCULATING AVERAGE WAITING TIME AND AVERAGE TURN AROUND
TIME
void Calculate()
{
int i;
//For the 1st process
Wt[1]=0;
for(i=2;i<=n;i++)
{
Wt[i]=Bu[i-1]+Wt[i-1];
}
for(i=1;i<=n;i++)
1.4OUTPUT:
GANTT CHART
-----------------------------------------------------------
| u | y | r |
-----------------------------------------------------------
0 14 22 35
-----------------------------------------------------------
1.5QUESTIONS:
(a)What would be two major advantages and two disadvantages of FCFS scheduling?
Program No: 2
TITLE: Simulation of the CPU scheduling algorithm
Non-Preemptive SJF
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
SJF: Shortest Job First algorithm associates with each process the length of the latter‟s
next CPU burst. When the CPU is available, it is assigned to the process that has the
smallest next CPU burst.
1.CODING:
void main()
{
clrscr();
Getdata();
Sjf();
getch();
}
1.4OUTPUT:
AverageWaiting Time=10.33 ms
GANTT CHART
--------------------------------------------------------------------
| u | t | y |
-----------------------------------------------------------
0 14 20 26
--------------------------------------------------------------------
1.5QUESTIONS:
(a)What would be two major advantages and two disadvantages of SJF scheduling?
Program No: 3
TITLE: Simulation of the CPU scheduling algorithm
Non-Preemptive Priority
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
PRIORITY: A priority is associated with each process; the CPU is allocated to the
process with the highest priority.
1.3CODING:
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
void main()
{
clrscr();
int x,n,p[10],pp[10],pt[10],w[10],t[10],awt,atat,i;
printf("Enter the number of process : ");
scanf("%d",&n);
printf("\n Enter process : time priorities \n");
for(i=0;i<n;i++)
{
printf("\nProcess no %d : ",i+1);
scanf("%d %d",&pt[i],&pp[i]);
p[i]=i+1;
}
for(i=0;i<n-1;i++)
{
Process no 1 : 3
5
Process no 2 : 1
6
Process no 3 : 2
7
3 2 0 2 7
2 1 2 3 6
1 3 3 6 5
1.5QUESTIONS:
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
ROUND ROBIN: The round robin scheduling algorithm is designed especially for
time-sharing systems. A small unit of time ,called a time quantum,or time slice is
defined .The ready queue is treated as a circular queue.The CPU scheduler goes around
the ready queue, allocating the CPU to each process for a time interval of up to 1 time
quantum.
1.3CODING:
#include<stdio.h>
#include<conio.h>
void main()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
int i,count=0,swt=0,stat=0,temp,sq=0;
float awt=0.0,atat=0.0;
clrscr();
printf("Enter number of processes:");
scanf("%d",&n);
printf("Enter burst time for sequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("Enter time quantum:");
scanf("%d",&tq);
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
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];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("\nProcess_no\tBurst_time\tWait_time\tTurn_around_t
ime");
for(i=0;i<n;i++)
printf("\n%d\t\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
printf("\nAvg wait time is %f\nAvg turn around time is
%f",awt,atat);
getch();
}
1.5QUESTIONS:
Program No: 5
TITLE – Implementation of Process Synchronization
(Producer / Consumer Problem)
1.1 Objective 1.2 Theories and Logic 1.3. Coding .1.4 Output 1.5 Questions
Two condition variables control access to the buffer. One condition variable is used to
tell if the buffer is full, and the other is used to tell if the buffer is empty. When the
producer wants to add an item to the buffer, it checks to see if the buffer is full; if it is
full the producer blocks on the cond_wait() call, waiting for an item to be removed from
the buffer. When the consumer removes an item from the buffer, the buffer is no longer
full, so the producer is awakened from the cond_wait() call. The producer is then
allowed to add another item to the buffer.
The consumer works, in many ways, the same as the producer. The consumer uses the
other condition variable to determine if the buffer is empty. When the consumer wants
to remove an item from the buffer, it checks to see if it is empty. If the buffer is empty,
the consumer then blocks on the cond_wait() call, waiting for an item to be added to the
buffer. When the producer adds an item to the buffer, the consumer's condition is
satisfied, so it can then remove an item from the buffer.
The example copies a file by reading data into a shared buffer (producer) and then
writing data out to the new file (consumer). The Buf data structure is used to hold both
the buffered data and the condition variables that control the flow of the data.
The main thread opens both files, initializes the Buf data structure, creates the consumer
thread, and then assumes the role of the producer. The producer reads data from the
input file, then places the data into an open buffer position. If no buffer positions are
available, then the producer waits via the cond_wait () call. After the producer has read
all the data from the input file, it closes the file and waits for (joins) the consumer
thread.
If the input file and the output file were residing on different physical disks, then this
example could execute the reads and writes in parallel. This parallelism would
significantly increase the throughput of the example through the use of threads.
1.3 CODING:
#define _REEENTRANT
#include <stdio.h>
#include <thread.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
struct {
char buffer[BUFCNT][BUFSIZE];
int byteinbuf[BUFCNT];
mutex_t buflock;
mutex_t donelock;
cond_t adddata;
cond_t remdata;
int nextadd, nextrem, occ, done;
} Buf;
/* function prototype */
void *consumer(void *);
thr_setconcurrency(2);
/* the producer ! */
while (1) {
mutex_unlock(&Buf.donelock);
close(ifd);
/* check to see if any buffers are filled or if the done flag is set */
while (1) {
1.5 OUTPUT:
1.6QUESTIONS:
(a) Can you achieve the process synchronization in producer consumer problem
using the counting semaphores?
(b) Which algorithm gives the deadlock free result in producer consumer problem?
Program No: 6
TITLE – Simulation of Critical section problem using Dekker’s Algorithm
1.1 Objective 1.2 Theory 1.3 Logic 1.4. Coding 1.5 Output 1.6 Questions
1.3 Algorithm:
{ for p1 }
repeat
if turn = 0 then
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
begin
while turn = 0 do ;
end
CS
turn:=0
non-CS
until false
1.4 Coding :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int choice;
int c1=1,c2=1,turn=1;
clrscr();
do
{
printf("\n1.Process 1 Enter");
printf("\n2.Process 2 Enter");
printf("\n3.Both Process Enter");
printf("\n4.Exit");
scanf("%d",&choice);
if (choice==1)
{
c1=0;
while (c2==0)
{
if (turn==2)
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
c1=1;
while (turn==2);
c1=0;
}
printf("\nProcess P1 enters the critical section");
c1=1;
turn=2;
}while (choice!=4);
}
1.5Output:
Enter choice 3
1.7 Questions:
ProgramNo: 7
TITLE –Simulation of Deadlock prevention and avoidance problem through Banker„s
algo
1.1 Objective 1.2 Theory 1.3 Logic 1.4 Coding 1.5 Output 1.6 Questions
1.2 Theory: - The Banker's algorithm is run by the operating system whenever a
process requests resources.The algorithm prevents deadlock by denying or postponing
the request if it determines that accepting the request could put the system in an unsafe
state (one where deadlock could occur).
Resources
1.3 Algorithm:
while () {
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
Temp[j]=Available[j] for all j
Find an i such that
a) Done[i] = False
b) Still_Needs[i,j] <= Temp[j]
if so {
Temp[j] += Allocated[i,j] for all j
Done[i] = TRUE}
}
else if Done[i] = TRUE for all i then state is safe
else state is unsafe
}
1.4 Coding:
ValidateRequest()
r = 0 to Maximum Processes
c = 0 to Maximum Resources
3).if any of the (1 & 2 )above exist return the specified error
and Show the message box indicating the error.
4).Now Allocate the Resources to the processes. So we can check the deadlock
Alloc[r][c] += Request[r];
Available[c]-=Request[c];
if system is in SafeState()
then
Signal to the system that system is in safe state
Alloc[r][c] -= Request[c];
Available[c]+=Request[c];
and signal to the system that unsafe state can occur, so the
request cannot be fulfilled and return to the calling functions.
--------------------------------------------------------------------------------------
Safestate()
r = 0 to Maximum Processes
c = 0 to Maximum Resources
2). Take a Matrix that can store the total no of resources Process[].
Assign every process a positive no
Process[r] = r;
3). Find a process in the List that satisfies the following condition.
Claim[r][c] - Alloc[r][c] ) <= tmpAvail[c]
If Process exits Mark that Process with some indicator. So, it
will not take part in the search.
Point 3 is implemented in the following code.
//////
while( Loop )
{
//////
for( i = 0; i < MAXPRO; i++ )
{
if( Process[i] != -1 )
{
Count = 0;
//////
for( int j = 0; j < MAXRES; j++ )
{
else
{
Check = false;
break;
}
}
//////
if( Count == MAXRES )
{
Check = true;
break;
}
}
//////
if( Check == true )
{
//////
for( int n=0; n < MAXRES; n++ )
{
tmpAvail[n]+=Alloc[i][n];
}
////// // Process Marked
Process[i] = -1;
Check = false;
}
4). Other wise simply go out of the search loop.
else
{
Loop = false;
}
}
//////
Count = 0;
return (Check);
}
1.5 Output:
Input:
Total Resources: Inputs the total resources.
Max Demand: Input the Maximum demand.
Current Need: Input the Current need of the processes.
Output:
Allocated: Shows the Allocated resources by the processes.
Available: Shows the available resources in the system.
Claimed: Shows the Total resources claimed by processes.
Still Needed: Shows the resources that are still needed by processes.
Summary:
Summary: Shows the summary of functions that are already performed.
1.6 Questions:
(a)List three examples of deadlock that are not related to a computer system
environment.
(b)Is it possible to have a deadlock involving only one single process. Explain your
answer.
Program No: 8
TITLE: Simulation of FIFO page replacement algorithm
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
1.3CODING:
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int flag1=0,flag2=0,pf=0,frsize=3,top=0;
clrscr();
for(i=0;i<3;i++)
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0;
flag2=0;
for(i=0;i<12;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("Number of page faults : %d ",pf);
getch();
}
void display()
{
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
int i;
printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}
1.4OUTPUT:
2 -1 -1
2 3 -1
2 3 -1
2 3 1
5 3 1
5 2 1
5 2 4
5 2 4
3 2 4
3 2 4
3 5 4
3 5 2
1.5QUESTIONS:
Program No: 9
TITLE: Simulation of LRU page replacement algorithm
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
1.3CODING:
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;
clrscr();
for(i=0;i<3;i++)
{
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1;
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;
}
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
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]);
}
1.4OUTPUT:
2 -1 -1
2 3 -1
2 3 -1
2 3 1
2 5 1
2 5 1
2 5 4
2 5 4
3 5 4
3 5 2
3 5 2
3 5 2
no of page faults : 4
1.5QUESTIONS:
Program No: 10
TITLE: Simulation of Optimal page replacement algorithm
1.1 Objective 1.2 Theory & Logic 1.3 Coding 1.4Output 1.5Questions
1.3CODING:
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
if(flag2==0)
{
for(i=0;i<3;i++)
lg[i]=0;
for(i=0;i<frsize;i++)
{
for(k=j+1;k<12;k++)
{
if(fr[i]==p[k])
{
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
lg[i]=k-j;
break;
}
}
}
found=0;
for(i=0;i<frsize;i++)
{
if(lg[i]==0)
{
index=i;
found=1;
break;
}
}
if(found==0)
{
max=lg[0];
index=0;
for(i=1;i<frsize;i++)
{
if(max<lg[i])
{
max=lg[i];
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]);
}
Operating System Lab (RCS-451)
MGM’s College of Engineering & Technology, Noida Department of Computer Science & Engineering
1.4OUTPUT:
2 -1 -1
2 3 -1
2 3 -1
231
235
235
435
435
435
235
235
235
no of page faults : 3
1.5QUESTIONS:
Program No: 11
TITLE – Synchronization of POSIX thread using mutex variable.
1.1 Objective 1.2 Theory 1.3 Logic 1.4 Coding 1.5 Output 1.6 Questions
1.1 OBJECTIVE: Write a Program for synchronizing POSIX thread using Murex
variable.
1.2 THEORY :
What is a Thread?
Synchronization
Mutex variable:
A mutex lock is the simplest form of lock, providing mutually exclusive access (hence
the term “mutex”) to a shared resource. Threads wanting to access a resource protected
by a mutex lock must first acquire the lock. Only one thread at a time may acquire the
lock. Any other threads attempting to acquire the lock are blocked until the owner
relinquishes it.
Mutex is an abbreviation for "mutual exclusion". Mutex variables are one of the
primary means of implementing thread synchronization and for protecting shared data
when multiple writes occur.
A mutex variable acts like a "lock" protecting access to a shared data resource. The
basic concept of a mutex as used in Pthreads is that only one thread can lock (or own) a
mutex variable at any given time. Thus, even if several threads try to lock a mutex only
one thread will be successful. No other thread can own that mutex until the owning
thread unlocks that mutex. Threads must "take turns" accessing protected data.
1.3 LOGIC:
This program illustrates the use of mutex variables in a threads program that performs a
dot product. The main data is made available to all threads through a globally accessible
structure. Each thread works on a different part of the data. The main thread waits for
all the threads to complete their computations, and then it prints the resulting sum.
The main program creates threads which do all the work and then print out result
upon completion. Before creating the threads, the input data is created. Since all threads
update a shared structure, we need a mutex for mutual exclusion. The main thread needs
to wait for all threads to complete, it waits for each one of the threads. We specify a
thread attribute value that allows the main thread to join with the threads it creates. Note
also that we free up handles when they are no longer needed.
1.4 CODING:
#include <pthread.h>
#include <stdio.h>
#include <malloc.h>
/* The following structure contains the necessary information to allow the function
"dot prod" to access its input data and place its output into the structure. */
typedef struct
{
double *a;
double *b;
double sum;
int veclen;
#define NUMTHRDS 4
DOTDATA dotstr;
pthread_t callThd[NUMTHRDS];
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
/* Perform the dot product and assign result to the appropriate variable in the
structure. */
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
/* Lock a mutex prior to updating the value in the shared structure, and unlock it
upon udating. */
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
dotstr.veclen = VECLEN;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_destroy(&attr);
1.5 OUTPUT:
a = 3i + 5j - 2k
b = 2i - 2j - 2k.
1.6 QUESTIONS:
(c) How the mutex variables and condition variables are different?
Program No: 12
TITLE – Synchronization of POSIX thread using Condition variables
1.1 Objective 1.2 Theory 1.3 Logic 1.4. Coding 1.5 Output 1.6 Questions
1.1 OBJECTIVE: Write a Program for synchronizing POSIX thread using condition
variables.
Synchronization
Condition variables provide yet another way for threads to synchronize. While
mutexes implement synchronization by controlling thread access to data,
condition variables allow threads to synchronize based upon the actual value of
data.
This simple example code demonstrates the use of several Pthread condition variable
routines. The main routine creates three threads. Two of the threads perform work and
update a "count" variable. The third thread waits until the count variable reaches a
specified value.
This program locks mutex and wait for signal. Note that the pthread_cond_wait
routine will automatically and atomically unlock mutex while it waits. Also, note that if
COUNT_LIMIT is reached before this routine is run by the waiting thread, the loop will
be skipped to prevent pthread_cond_wait from never returning.
1.4 CODING:
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 3
#define TCOUNT 10
#define COUNT_LIMIT 12
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
/* Check the value of count and signal waiting thread when condition is reached.
Note that this occurs while mutex is locked. */
if (count == COUNT_LIMIT)
{
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %d, count = %d Threshold reached.\n", *my_id, count);
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\n", *my_id, count);
pthread_mutex_unlock(&count_mutex);
pthread_mutex_lock(&count_mutex);
if (count<COUNT_LIMIT) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %d Condition signal
received.\n", *my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
pthread_mutex_init(&count_mutex, NULL);
pthread_cond_init (&count_threshold_cv, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]);
pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]);
pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]);
1.5 OUTPUT:
1.6 QUESTIONS: