OS Lab Manual
OS Lab Manual
OS Lab Manual
Expt. Page
Title No
No.
INSTRUCTIONS 3
The danger of injury or death from electrical shock, fire, or explosion is present while conducting
experiments in this laboratory. To work safely, it is important that you understand the prudent
practices necessary to minimize the risks and what to do if there is an accident.
FIRE: Transistors and other components can become extremely hot and cause severe burns
iftouched. If resistors or other components on your proto-board catch fire, turn off the power
supply and notify the instructor. If electronic instruments catch fire, turn OFF the main MCB (Red
Color). These small electrical fires extinguish quickly after the power is shut off. Avoid using fire
extinguishers on electronic instruments.
EXPLOSION: When using electrolytic capacitors, be careful to observe proper polarity and donot
exceed the voltage rating. Electrolytic capacitors can explode and cause injury. Proceed to Student
Health Services, if needed.
GENERAL INSTRUCTIONS:
1. Heading: The experiment identification (number) should be at the top of each page.
2. Diagram: Relevant diagrams should be drawn and labeled so that the actual experiment could be
easily duplicated at any time in the future. Be especially careful to record all circuit changes made
during the experiment.
4. Equipment List: List those items of equipment which have a direct effect on the accuracy of the
data.
6. Data: Think carefully about what data is required and prepare suitable data tables. Record
instrument readings directly. Do not use calculated results in place of direct data; however,
calculated results may be recorded in the same table with the direct data. Data tables should be
clearly identified and each data column labeled and headed by the proper units of measure.
7. Calculations: Not always necessary but equations and sample calculations are often given to
illustrate the treatment of the experimental data in obtaining the results.
8. Graphs: Graphs are used to present large amounts of data in a concise visual form. Data to be
presented in graphical form should be plotted in the laboratory so that any questionable data points
can be checked while the experiment is still set up. Give all graphs a short descriptive title. Label
and scale the axes. Use units of measure. Label each curve if more than one on a graph.
9. Results: The results should be presented in a form which makes the interpretation easy. Large
amounts of numerical results are generally presented in graphical form. Tables are generally used
for small amounts of results. Theoretical and experimental results should be on the same
graph or arrange in the same table in a way for easy correlation of these results.
10. Conclusion: This is your interpretation of the results of the experiment as an engineer. Be brief
and specific. Give reasons for important discrepancies
Experiment No 1
Don Bosco College of Engineering, Fatorda- Goa Page 4
Laboratory Manual (Operating System)
Aim: To study the concept of operating system and different types of operating system.
Requirements:
Software requirements: Windows Operating system, MS Word &Ms Paint
Theory:
An Operating System performs all the basic tasks like managing file,process, and memory. Thus
operating system acts as manager of all the resources, i.e. resource manager.
network.
Advantages of Distributed Operating System:-
-Failure of one will not affect the other network communication, as all systems are independent
from each other
-Electronic mail increases the data exchange speed
-Since resources are being shared, computation is highly fast and durable
-Load on host computer reduces
Don Bosco College of Engineering, Fatorda- Goa Page 6
Laboratory Manual (Operating System)
-These systems are easily scalable as many systems can be easily added to the network
-Delay in data processing reduces
Advantages of RTOS:-
-Maximum Consumption: Maximum utilization of devices and system,thus more output from all the
resources
-Task Shifting: Time assigned for shifting tasks in these systems are very less. For example in older
systems it takes about 10 micro seconds in shifting one task to another and in latest systems it takes
3 micro seconds.
-Focus on Application: Focus on running applications and less importance to applications which are
in queue.
-Real time operating system in embedded system: Since size of program is small, RTOS can also be
used in embedded systems like in transport and others.
-Error Free: These types of systems are errorfree.
Memory Allocation: Memory allocation is best managed in these type of systems.
Disadvantages of RTOS:-
-Limited Tasks: Very few tasks run at the same time and their concentration is very less on few
applications to avoid errors.
-Use heavy system resources: Sometimes the system resources are not so good and they are
expensive as well.
Conclusion: Concept of operating system and different types of operating systems and their
working is studied successfully.
Experiment No 2a
Don Bosco College of Engineering, Fatorda- Goa Page 9
Laboratory Manual (Operating System)
Aim:To study and implement non-preemptive “First come First serve” process scheduling
algorithm.
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer
Theory:
First Come First Served is the simplest scheduling algorithm. It is based on the principle that the
first item to enter the queue is the first item that gets to leave the queue. This means that scheduling
happens based on the arrival time of the process. This algorithm does not allow preemption. This
could lead to inefficient use of resources. Interactive process may not get scheduled as CPU
processes cannot be preempted.
Important calculations:
Completion Time: Time taken for the execution to complete, starting from arrival time.
Turn Around Time: Time taken to complete after arrival. In simple words, it is the
differencebetween the Completion time and the Arrival time.
Waiting Time: Total time the process has to wait before it's execution begins. It is the
differencebetween the Turn Around time and the Burst time of the process.
Example:
Consider the processes P1, P2, P3, P4 given in the below table, arrives for execution in the same
order, with Arrival Time0, and given Burst Time, let's find the average waiting time using the
FCFS scheduling algorithm.
• P1 requires 21ms for completion, hence waiting time for P2 will be 21ms
• For process P4 it will be the sum of execution times of P1, P2 and P3= 30ms
Algorithm
Step 2: Assign the process to the CPU according to the priority, higher priority process will get the
CPU first than lower priority process.
Step 3: If two processes have similar priority then FCFS is used to break the tie.
Step8: stop
Program
importjava.util.*;
classFcfs
{
private static Scanner sn;
public static void main(String[] args)
{
intid[]=new int[20];
intbtime[]=new int[20];
intwtime[]=new int[20];
inttotal=0;
Aim: To study and implement non-preemptive “Shortest Job First”process scheduling algorithm.
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer
Theory:
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process
with the smallest execution time to execute next. SJN is a non-preemptive algorithm.
In non-preemptive category of “shortest Job first “algorithm, once CPU given to the process it cannot
be preempted until completes its CPU burst
Shortest Job first has the advantage of having minimum average waiting time among all scheduling
algorithms since it adapts Greedy approach. It may cause starvation if shorter processes keep
coming. This problem can be solved using the concept of aging. It is practically infeasible as
Operating System may not know burst time and therefore may not sort them. While it is not possible
to predict execution time, several methods can be used to estimate the execution time for a job, such
as a weighted average of previous execution times. SJF can be used in specialized environments
where accurate estimates of running time are available.
Example:
Algorithm:
Step 1- Sort all the processes in increasing order according to burst time.
(i.e. two processes having same next CPU burst), apply FCFS algorithm.
Program:
importjava.util.*;
intat[] = new int[n]; // at means arrival timeintbt[] = new int[n]; //btmeans burst timeintct[] = new
int[n]; //ctmeans complete timeintta[] = new int[n]; //tameansturn around timeintwt[] = new
int[n]; //wtmeans waiting time
intf[] = new int[n]; // f means it is flag it checks process is completed or notintst=0, tot=0;
floatavgwt=0, avgta=0;
for(inti=0;i<n;i++)
{
System.out.println ("enter process " + (i+1) + " arrival time:"); at[i] = sc.nextInt();
System.out.println ("enter process " + (i+1) + " brust time:");
bt[i] = sc.nextInt();
pid[i] = i+1;
f[i] = 0;
booleana= true;
while(true)
{
intc=n, min=999;
c=i;
}
}
/* If c==n means c value can not updated because no process arrival time< system time so we
increase the system time */
if(c==n)
st++;
else
{
ct[c]=st+bt[c];
st+=bt[c];
ta[c]=ct[c]-at[c];
wt[c]=ta[c]-bt[c];
f[c]=1;
tot++;
}
}
Sample Output:
enter no of process:4
averagetat is 8.0
averagewt is 4.0
Aim:To study and implement preemptive “Shortest Job First” process scheduling algorithm.
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer
Theory:In Preemptive Shortest Job First Scheduling, jobs are put into ready queue as theyarrive,
but as a process with short burst time arrives, the existing process is preempted or removed from
execution, and the shorter job is executed first. It is also known as shortest remaining time first
algorithm.
Example:
P1 arrives first, hence it's execution starts immediately, but just after 1ms, process P2 arrives
withaburst time of 3ms which is less than the burst time of P1, hence the process P1 (1 ms done,
20 ms left) is preempted and process P2 is executed.
As P2 is getting executed, after 1ms, P3 arrives, but it has a burst time greater than that of P2, hence
execution of P2 continues. But after another millisecond, P4 arrives with a burst time of 2ms, as a
result P2 (2 ms done, 1ms left) is preempted and P4 is executed.
After the completion of P4, process P2 is picked up and finishes, then P2 will get executed and at
last P1.
Implementation:
Step 1.1 - Find process with minimum remaining time at every single time lap.
Step 2- Find waiting time and turnaround time and print the same.
Program:
importjava.util.*;
while(true){
intmin=99,c=n;
if(tot==n)
break;
for( i=0;i<n;i++)
{
if((at[i]<=st) && (f[i]==0) && (bt[i]<min))
{
min=bt[i];
c=i;
}
}
if(c==n)
st++;
else
{
bt[c]--;
st++;
if(bt[c]==0)
{
ct[c]= st;
f[c]=1;
tot++;
}
}
}
for(i=0;i<n;i++)
{
ta[i] = ct[i] - at[i];
wt[i] = ta[i] - k[i];
avgwt+= wt[i];
Sample Output
enter no of process: 4
averagetat is 7.0
averagewt is 3.0
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer
Theory:
This scheduling algorithm can be thought of as a preemptive version of the FCFS scheduling
algorithm. Jobs are processed in a FIFO sequence but each job is only allowed to run for a pre-
determined and limited amount of time. This time interval is termed as 'time-slice' or 'quantum'.
Irrespective of whether a job is complete or not, once it exceeds the time slice it is preempted and
the next job is scheduled. The preempted process is placed at the back of the queue and is resumed
when it is scheduled again. Smaller the time slice, higher the number of times the system cycles
through the processes. High frequency of context switching may sometimes prove costly if time
spent doing work is less than the number of jumps taken.
Example:
Algorithm
Step 1 - Create an array rem_bt[] to keep track of remaining burst time of processes. This array
is
initially a copy of bt[] (burst times array)
Step 2 - Create another array wt[] to store waiting times of processes. Initialize this array as 0.
Step 3 - Initialize time : t = 0
Step 4 - Keep traversing the all processes while all processes are not done. Do following for i'th
process if it is not done yet.
Step 5 -
a- If rem_bt[i] > quantum
(i) t = t + quantum
(ii) bt_rem[i] -= quantum;
c- Else // Last cycle for this process
Don Bosco College of Engineering, Fatorda- Goa Page 22
Laboratory Manual (Operating System)
(i) t = t + bt_rem[i];
(ii) wt[i] = t - bt[i]
(ii) bt_rem[i] = 0; // This process is over
Program
importjava.io.*;
classround
{
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
inti,j,k,q,sum=0;
System.out.println("Enter number of process:");
intn=Integer.parseInt(in.readLine());
intbt[]=new int[n];
intwt[]=new int[n];
inttat[]=new int[n];
inta[]=new int[n];
System.out.println("Enter brust Time:");
for(i=0;i<n;i++)
{
System.out.println("Enter brust Time for"+(i+1));
bt[i]=Integer.parseInt(in.readLine());
}
System.out.println("Enter Time quantum:");
q=Integer.parseInt(in.readLine());
for(i=0;i<n;i++)
a[i]=bt[i];
for(i=0;i<n;i++)
wt[i]=0;
do
{
for(i=0;i<n;i++)
{
if(bt[i]>q)
{
bt[i]-=q;
for(j=0;j<n;j++)
{
if((j!=i)&&(bt[j]!=0))
wt[j]+=q;
}
}
else
{
for(j=0;j<n;j++)
{
Sample Output
Enter number of process:3
Enter brust Time:
Enter brust Time for1 :3
Enter brust Time for2 :4
Enter brust Time for3 :3
Enter Time quantum: 1
Process BT WT TAT
process1 3 4 7
process2 4 6 10
process3 3 6 9
average waiting time: 5.3333335
averagetat is 8.0
averagewt is 4.0
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer
Theory:
What is a Thread?
A thread is a path of execution within a process. Thread is also known as lightweight process. A
process can contain multiple threads.
Why Multithreading?
The idea is achieve parallelism by dividing a process into multiple threads. For example, in a
browser, multiple tabs can be different threads. MS word uses multiple threads, one thread to
format the text, other thread to process inputs etc.
Similarities between Process and Thread
1) Like Processes, thread share CPU and only one thread remain active at a time.
2) Like processes, threads within a processes execute sequentially
3) Like Processes, threads can create children’s
4) Like processes, In Kernal/Supervisor mode, if one thread is blocked, other threads can still
run.
Dissimilarities between Process and Thread
1) Unlike processes, threads are not independent of each other
2) Unlike processes, all threads can access every address in task
3) Unlike processes, threads are created to support each other thereby to execute process
successfully
4) Different processes originating from different user may or may not cooperate each other.
1. Responsiveness: If the process is divided into multiple threads, if one thread completed its
execution, then its output can be immediately responded.
2. Faster context switch: Context switch time between threads is less compared to process context
switch. Process context switch is more overhead for CPU.
4. Resource sharing: Resources like code, data and file can be shared among all threads within a
process.
Note : stack and registers can’t be shared among the threads. Each thread have its own stack and
registers.
6. Enhanced Throughput of the system: If process is divided into multiple threads and each thread
function is considered as one job, then the number of jobs completed per unit time is increased.
This improves the throughput of the system.
There are two types of thread.
User Level Thread
Kernel Level Thread
To start the Java thread you will call its start() method, like this:
thread.start();
This example doesn't specify any code for the thread to execute. The thread will stop again right
away after it is started.
There are two ways to specify what code the thread should execute. The first is to create a subclass
of Thread and override the run() method. The second method is to pass an object that implements
Runnable (java.lang.Runnable to the Thread constructor. Both methods are covered below.
Thread Subclass
The first way to specify what code a thread is to run, is to create a subclass of Thread and override
the run() method. The run() method is what is executed by the thread after you call start().
To create and start the above thread you can do like this:
The start() call will return as soon as the thread is started. It will not wait until the run() method
is done. The run() method will execute as if executed by a different CPU. When the run() method
executes it will print out the text "MyThread running".
This example will print out the text "Thread running" once the run() method is executed by the
new thread.
The second way to specify what code a thread should run is by creating a class that implements
java.lang.Runnable. The Runnable object can be executed by a Thread.
To have the run() method executed by a thread, pass an instance of MyRunnable to a Thread in
its constructor. Here is how that is done:
When the thread is started it will call the run() method of the MyRunnable instance instead of
executing it's own run() method. The above example would print out the text "MyRunnable
running".
Program:
Experiment No. 5
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer
THEORY:
What is a System Call?
When a program in user mode requires access to RAM or a hardware resource, it must ask the ke
rnel to provide access to that resource. This is done via something called a system call.When a pr
ogram makes a system call, the mode is switched from user mode to kernel mode. This is called a
context switch, and then the kernel provides the resource which the program requested. After tha
t, another context switch happens which results in change of mode from kernel mode back to user
mode.
Generally, system calls are made by the user level programs in the following situations:
-Creating, opening, closing and deleting files in the file system.
-Creating and managing new processes.
-Creating a connection in the network, sending and receiving packets.
-Requesting access to a hardware device, like a mouse or a printer.
memset() : This function fills the first n bytes of the memory area pointed to by s with the consta
nt byte c.
fopen() : This function opens the file whose name is the string pointed to by its first argument an
d associates a stream with it.
getcwd() : This function return a null-terminated string containing an absolute pathname that is t
he current working directory of the calling process
getuid() : This function returns the real user ID of the calling process
snprintf() : This function produces output according to a format and writes the output to a buffer.
fflush() : This function forces a write of all user space buffered data on to a particular stream
fclose() : This function flushes the associated stream and closes the underlying file descriptor.
system() : This function executes a command
sleep() : This function makes the calling process sleep until specified seconds have elapsed or a s
ignal arrives which is not ignored.
The w command displays a list of all logged in to the server and what they are doing.
This command is similar to who command, but ends up displaying more information about logge
d in users.
Syntax:
w
w [UserNameHere]
w [UserNameHere1] [UserNameHere2]
w [options]
w [options] [UserNameHere]
IMPORTANCE OF UTMP
In Linux/Unix operating systems everything is logged somewhere. Most of the system logs are lo
gged in to /var/log folder. This folder contains logs related to different services and applications.
In this folder we have some files such as utmp, wtmp and btmp. These files contains all the detail
s about login’s and logout’s which are from local as well as from remote systems and system stat
us such as uptime etc.
“utmp” will give you complete picture of users logins at which terminals, logouts, system events
and current status of the system, system boot time (used by uptime) etc.
“wtmp” gives historical data of utmp.
“btmp” records only failed login attempts.
We can read this file with only last command. last command is one of the important command w
hich will give you how logged in, when they logged in and when they logged out etc info on the s
creen.
PROGRAM:
i. System call for all logged in
#include<stdio.h>
#include<sys/utsname.h>
#include<utmp.h>
int main(void)
{
structutmp *n;
char *a;
int i;
setutent();
n=getutent();
while(n!=NULL)
{
if(n->ut_type==7)
{
printf("%9s",n->ut_user);
printf("%12s",n->ut_line);
a=ctime(&n->ut_time);
printf(" ");
for(i=4;i<16;i++)
printf("%c",a[i]);
printf(" (");
printf("%s10",n->ut_host);
printf(")");
printf("\n");
}
n=getutent();
}
}
Output:
pid = fork();
CONCLUSION:System calls for fork and all logged was studied and implemented successfully.
Experiment No. 6
Requirements:
Software requirements: Windows Operating system, Net beans, JDK 7 or above
Hardware requirements: Personal/Desktop computer
Theory:
The Dining Philosopher Problem – The Dining Philosopher Problem states that K philosophers
seated around a circular table with one chopstick between each pair of philosophers. There is one
chopstick between each philosopher. A philosopher may eat if he can pickup the two chopsticks
adjacent to him. One chopstick may be picked up by any one of its adjacent followers but not both.
When a philosopher wants to eat the rice, he will wait for the chopstick at his left and picks up that
chopstick. Then he waits for the right chopstick to be available, and then picks it too. After eating,
he puts both the chopsticks down.
But if all five philosophers are hungry simultaneously, and each of them pickup one chopstick,
then a deadlock situation occurs because they will be waiting for another chopstick forever. The
possible solutions for this are:
A philosopher must be allowed to pick up the chopsticks only if both the left and right
chopsticks are available.
Allow only four philosophers to sit at the table. That way, if all the four philosophers pick up
four chopsticks, there will be one chopstick left on the table. So, one philosopher can start eating
and eventually, two chopsticks will be available. In this way, deadlocks can be avoided.
There are three states of philosopher: THINKING, HUNGRY and EATING. Here there are
two semaphores: Mutex and a semaphore array for the philosophers. Mutex is used such that
no two philosophers may access the pickup or putdown at the same time. The array is used to
void release() {
mutex.release();
}
booleanisFree() {
returnmutex.availablePermits() > 0;
}
}
while (true) {
leftFork.grab();
System.out.println("Philosopher #" + number + " grabs left fork.");
rightFork.grab();
System.out.println("Philosopher #" + number + " grabs right fork.");
eat();
leftFork.release();
System.out.println("Philosopher #" + number + " releases left fork.");
rightFork.release();
System.out.println("Philosopher #" + number + " releases right fork.");
}
}
void eat() {
try {
intsleepTime = ThreadLocalRandom.current().nextInt(0, 1000);
System.out.println("Philosopher #" + " eats for " + sleepTime);
Thread.sleep(sleepTime);
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
while (true) {
try {
// sleep 1 sec
Thread.sleep(1000);
// check for deadlock
boolean deadlock = true;
for (Fork f : forks) {
Output:
run:
Dining philosophers problem.
Hi! I'm philosopher #0
Philosopher #0 grabs left fork.
Philosopher #0 grabs right fork.
Philosopher # eats for 997
Hi! I'm philosopher #1
Hi! I'm philosopher #3
Philosopher #3 grabs left fork.
Philosopher #3 grabs right fork.
Philosopher # eats for 925
Hi! I'm philosopher #2
Philosopher #2 grabs left fork.
Hi! I'm philosopher #4
Philosopher #3 releases left fork.
Philosopher #3 releases right fork.
Philosopher #2 grabs right fork.
Philosopher # eats for 938
Philosopher #4 grabs left fork.
Philosopher #0 releases left fork.
Philosopher #4 grabs right fork.
Philosopher # eats for 823
Philosopher #0 releases right fork.
Philosopher #1 grabs left fork.
Philosopher #4 releases left fork.
Experiment No. 7
Aim:To implement deadlock avoidance scheme using banker’s algorithm.
Requirements:
Theory:
Banker’s Algorithm:
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests for
safety by simulating the allocation for predetermined maximum possible amounts of all resources,
then makes an “s-state” check to test for possible activities, before deciding whether allocation
should be allowed to continue.
Following Data structures are used to implement the Banker’s Algorithm: Let ‘n’ be the number
of processes in the system and ‘m’ be the number of resources types.
Available:
It is a 1-d array of size ‘m’ indicating the number of available resources of each type.
Max:
It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a system.
Max[i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.
Allocation:
It is a 2-d array of size ‘n*m’ that defines the number of resources of each type currently
allocated to each process.
Need:
It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each process.
Need [ i, j ] = k means process Pi currently allocated ‘k’ instances of resource type Rj
Let Requesti be the request array for process Pi. Requesti [j] = k means process Pi wants k
instances of resource type Rj. When a request for resources is made by process Pi, the following
actions are taken:
1) If Requesti<= Needi
Goto step (2) ; otherwise, raise an error condition, since the process has exceeded its maximum
claim.
3) Have the system pretend to have allocated the requested resources to process Pi by modifying
the state as follows:
Safety Algorithm
The algorithm for finding out whether or not a system is in a safe state can be described as follows:
1) Let Work and Finish be vectors of length ‘m’ and ‘n’ respectively.
Initialize: Work = Available
Finish[i] = false; for i=1, 2, 3, 4….n
2) Find an i such that both
a) Finish[i] = false
b) Needi<= Work if no such i exists goto step (4)
3) Work = Work + Allocation
Finish[i] = true, then go to step (2)
4) if finish [i] = true for all i
Then the system is in a safe state and the sequence obtained is a safe sequence
Bankers Algorithm Program:
importjava.util.Scanner;
public class BankersAlgo
{
private int need[][],allocate[][],max[][],avail[][],np,nr;
sc.close();
}
privateint[][] calc_need()
{
for(int i=0;i<np;i++)
for(int j=0;j<nr;j++) //calculating need matrix
need[i][j]=max[i][j]-allocate[i][j];
return need;
}
privatebooleancheck(int i)
{
//checking if all resources for ith process can be allocated
for(int j=0;j<nr;j++)
if(avail[0][j]<need[i][j])
return false;
return true;
}
while(j<np)
{ //until all process allocated
boolean allocated=false;
for(int i=0;i<np;i++)
if(!done[i] && check(i)){ //trying to allocate
OUTPUT:
Safely allocated
Conclusion:Deadlock avoidance scheme using banker’s algorithm was successfully studied and
implemented.
Experiment No. 8
Aim:To study page replacement policies like
1. First-in-first-out
2. Least recently used(LRU)
Theory:
In multiprogramming system using dynamic partitioning there will come a time when all of the
processes in the main memory are in a blocked state and there is insufficient memory. To avoid
wasting processor time waiting for an active process to become unblocked. The OS will swap one
of the process out of the main memory to make room for a new process or for a process in
ReadySuspend state. Therefore,the OS must choose which pocess to replace.
Thus, when a page fault occurs, the OS has to change a page to remove from memory to make
room for the page that must be brought in. If the page to be removed has been modified while in
memory it must be written to disk to bring the disk copy up to date. Replacement algorithms can
affect the system's performance.
• First-In-First_Out
Replace the page that has been in memory longest, is the policy applied by FIFO. Pages
from memory are removed in round-robin fashion. Its advantage is it's simplicity.
• Least Recently Used Algorithm
This paging algorithm selects a page for replacement that has been unused for the longest
time.
• Optimal Page Replacement Policy
The idea is to replace the page that will not be referenced for the longest period of time.
1. FIFO ALGORITHM:
Step 1: Start
Step 2: create a queue to hold all pages in memory
Step 3: when the page is required replace the page at the head of the queue
Step 4: now the new page is inserted at the tail of the queue
Step 5: Stop
2. LRU ALGORITHM:
Step 1: Start
Step 2: Create a queue to hold all pages in memory
Step 3: When the page is required replace the page at the head of the queue
LRU PROGRAM
HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted
as HashMap<Key, Value> or HashMap<K, V>. ...
You must need to import java.util.HashMap or its super class in order to use the HashMap class
and methods.
Java HashSet class is a member of Java collections framework. It implements the Set interface. ...
HashSet is an unordered collection.
It does not maintain the order in which the elements are inserted. HashSet internally uses a
HashMap to store its elements
Iterators allow the caller to remove elements from the underlying collection during the iteration
with well-defined semantics. Method names have been improved.
package practice;
importjava.util.HashMap;
importjava.util.HashSet;
importjava.util.Iterator;
class LRU {
// Method to find page faults using indexes
staticintpageFaults(int pages[], int n, int capacity)
{
// To represent set of current pages. We use
// an unordered_set so that we quickly check
// if a page is present in set or not
HashSet<Integer> s = new HashSet<>(capacity);
// To store least recently used indexes
// of pages.
HashMap<Integer, Integer> indexes = new HashMap<>();
// Start from initial page
intpage_faults = 0;
for (int i=0; i<n; i++)
{
// Check if the set can hold more pages
if (s.size() < capacity) {
// Insert it into set if not present
// already which represents page fault
if (!s.contains(pages[i]))
{
s.add(pages[i]);
// increment page fault
page_faults++;
}
OUTPUT
FIFO PROGRAM
packagedbce;
import java.io.*;
public class FIFO {
public static void main(String[] args) throws IOException
{
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
int frames, pointer = 0, hit = 0, fault = 0,ref_len;
int buffer[];
intreferencepage[];
intmem_layout[][];
System.out.print("Please enter the number of Frames: ");
frames = Integer.parseInt(br.readLine());
System.out.print("Please enter the length of the Reference string: ");
ref_len = Integer.parseInt(br.readLine());
referencepage = new int[ref_len];
mem_layout = new int[ref_len][frames];
buffer = new int[frames];
for(int j = 0; j < frames; j++)
buffer[j] = -1;
System.out.print("Please enter the reference string: ");
for(int i = 0; i<ref_len; i++) {
referencepage[i] = Integer.parseInt(br.readLine());
}
System.out.println();
for(int i = 0; i<ref_len; i++) {
int search = -1;
OUTPUT
Please enter the number of Frames: 3
Please enter the length of the Reference string: 6
Please enter the reference string: 1
2
3
1
2
3
1 1 1 1 1 1
-1 2 2 2 2 2
-1 -1 3 3 3 3
Experiment No. 9a
Aim:To implement First Come First Serve Disk Scheduling Algorithm
Requirements:
Theory:
Consider a string of head movement as: 95, 180, 34, 119, 11, 123, 62, 64 with the Read-write head
initially at the track 50 and the tail track being at 199. Let us try to understand the logic of FCFS
algorithm.
All incoming requests are placed at the end of the queue. Whatever number that is next in the
queue will be the next number served. Using this algorithm doesn't provide the best results. To
determine the number of head movements you would simply find the number of tracks it took to
move from one request to the next. For this case it went from 50 to 95 to 180 and so on. From 50
to 95 it moved 45 tracks. If you tally up the total number of tracks you will find how many tracks
it had to go through before finishing the entire request. In this example, it had a total head
movement of 640 tracks. The disadvantage of this algorithm is noted by the oscillation from track
50 to track 180 and then back to track 11 to 123 then to 64. As you will soon see, this is the worse
algorithm that one can use.
Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested.
‘head’ is the position of disk head.
2. Server the request according to the order in which they arrive.
3. Increment the total seek count with this distance.
4. Currently serviced track position now becomes the new head position.
5. Go to step 2 until all tracks in request array have not been serviced.
Program: FCFS Disk scheduling
packagedbce;
importjava.util.*;
classfcfs_dsk
OUTPUT:
Enter no of cylinders
6
Enter the cylinder no.
Conclusion:First Come First Serve Disk Scheduling Algorithm was studied and implemented
successfully.
Experiment No. 9b
Aim:To implement Shortest Seek time First Disk Scheduling Algorithm
Theory:
In this case request is serviced according to next shortest distance. Starting at 50, the next shortest
distance would be 62 instead of 34 since it is only 12 tracks away from 62 and 16 tracks away
from 34. The process would continue until all the processes are taken care of. For example the next
case would be to move from 62 to 64 instead of 34 since there are only 2 tracks between them and
not 18 if it were to go the other way. Although this seems to be a better service being that it moved
a total of 236 tracks, this is not an optimal one. There is a great chance that starvation would take
place. The reason for this is if there were a lot of requests close to each other the other requests
will never be handled since the distance will always be greater.
Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested.
‘head’ is the position of disk head.
2. Find the positive distance of all tracks in the request array from head.
3. Find a track from requested array which has not been accessed/serviced yet and has minimum
distance from head.
4. Increment the total seek count with this distance.
5. Currently serviced track position now becomes the new head position.
6. Go to step 2 until all tracks in request array have not been serviced.
OUTPUT:
Total number of seek operations = 127
Seek Sequence is
50
48
60
92
11
Conclusion:Shortest Seek time First Disk Scheduling Algorithm was studied and implemented
successfully.
Experiment No. 10
Aim:To study the concept of shell scripting.
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Theory:
Shell scripting is writing a series of command for the shell to execute. It can combine lengthy and
repetitive sequences of commands into a single and simple script, which can be stored and executed
anytime. This reduces the effort required by the end user.
1) touch
Update the access and modification times of each FILE to the current time.
A FILE argument that does not exist is created empty, unless -c or -h
is supplied.
3) groupadd
groupadd command creates a new group account using the values specified on the
command line and the default values from the system. The new group will be entered into
the system files as needed.
Syntax: groupadd [options] group
4) useradd
useradd - create a new user or update default new user information
When invoked without the -D option, the useradd command creates a new user account
using the values specified on the command line and the default values from the system.
Depending on command line options, the useradd command will update system files and
may also create the new user’s home directory and copy initial files.
Syntax:
useradd [options] LOGIN
useradd -D
useradd -D [options]
5) mkdir
Create the DIRECTORY(ies), if they do not already exist.
Usage: mkdir [OPTION]... DIRECTORY...
6) rmdir
Remove the DIRECTORY(ies), if they are empty.
Usage: rmdir [OPTION]... DIRECTORY...
7) cd
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
Usage: cd [-L|[-P [-e]] [-@]] [dir]
8) pwd
Print the name of the current working directory.
Usage: pwd [-LP]
9) ps
Don Bosco College of Engineering, Fatorda- Goa Page 61
Laboratory Manual (Operating System)
It displays the list of processes which are currently running on the machine.
Usage: ps [options]
10) renice
Alter the priority of running processes.
Usage:
renice [-n] <priority> [-p|--pid] <pid>...
renice [-n] <priority> -g|--pgrp<pgid>...
renice [-n] <priority> -u|--user <user>...
11) uname
It gives information about unix system which you are using.
Usage: uname
e.g. Output: SunOS
PROGRAM 1:
while true
do
readch;
case $ch in
1)
if [ -f $filename ];
then
echo"File already existing"
else
touch $filename;
echo "File created "
ls -t | head -n 15
fi # end of if statement
ls -t | head -n 15
;;
3)
echo "Enter the file name to be delete: ";
read filename
rm -f $filename
echo "After deleting file: ";
ls -t | head -n 15
;;
4)
exit;
;;
esac # end of switch case
done
OUTPUT:
rahul@rahulUbuntu:~/Desktop/Scripts/output$ ls -l
total 8
1.Create File :
2.Rename a File :
3.Delete File :
4.Exit
1.Create File :
2.Rename a File :
3.Delete File :
4.Exit
do
readch;
case $ch in
1)
2)
echo "Memory map :";
free -m #u can use less /proc/meminfo
;;
3)
echo "Processprinformation : "; # u can use cat /proc/cpuinfo
cat /proc/cpuinfo
;;
4)
exit;
;;
esac # end of switch case
done
OUTPUT:
readch;
case $ch in
1)
if [ -d $dir ];
then
echo"Directory already existing"
else
mkdir $dir;
echo "Directory created "
ls -t | head -n 15
fi # end of if statement
;; # to break first switch case
2)
echo "Enter the Directory name to be delete : ";
readdir;
rmdir $dir;
echo "Directory Deleted successfully";
ls -t | head -n 15
;;
3)
echo "Changing current working directory to : enter the path ";
read path
cd $path
pwd
ls -i
;;
4)
echo "Current Working Directory : ";
pwd
;;
5)
OUTPUT:
rahul@rahulUbuntu:~/Desktop/Scripts/output$ ./A-4.sh
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
Enter your choice :
4
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
Enter your choice :
3
Changing current working directory to : enter the path
new
/home/rahul/Desktop/Scripts/output/new
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
PROGRAM 4:
while true
do
echo "1.Display Operating System name :";
echo "2.Display Operating System Version:";
echo "3.Display Login name :";
echo "4.Display Hostname :";
echo "5.Exit";
OUTPUT:
rahul@rahulUbuntu:~/Desktop/Scripts/output$ ./A-6.sh
1.Display Operating System name :
2.Display Operating System Version:
3.Display Login name :
4.Display Hostname :
5.Exit
Enter your choice :
1
Host Name :
rahulUbuntu
Conclusion: Shell scripting was successfully completed with implementation of few operating
system information related scripts.