You are on page 1of 71

LIST OF EXPERIMENTS

Subject: Operating System Year: 2018-2019

Class: T.E. Semester: V

Expt. Page
Title No
No.

LABORATORY SAFETY INFORMATION 2

INSTRUCTIONS 3

GUIDELINES FOR LABORATORY NOTEBOOK


4

1 Study the various types of operating systems 5-9


Study and implementation of Non pre-emptive CPU scheduling
2 10-17
algorithms.1)First Come First Serve2)Shortest Job First
Study and Implementation of Pre-emptive CPU scheduling
3 18-25
algorithms 1)Shortest Job First 2)Round Robin
4 Study and Implementation of threads using 26-32
1)Thread class2)Runnable interface
Study and Implementation of system calls for
5 33-37
1)Forking of child 2) list of logged in users
Study and implementation of process synchronization using semaphores 38-42
6
(Implementation of Dining philosopher example)
Study and Implementation of deadlock avoidance scheme 43-46
7
(Implementation of banker’s algorithm)
Study and Implementation of Page replacement method 47-52
8
1) First In First Out 2)Least Recently Used
Study and Implementation of Disk scheduling algorithms
9 1)Implementation of First come First Serve 53-58
2) Implementation of Shortest Seek Time First
Study and implementation of Schell Script for
1) Working on users and groups
10 2) Implementation of file operations 59-71
3) Display information of Operating System
4) Display information of memory map and processor

Instructor Incharge Laboratory Incharge Head of the Department

Don Bosco College of Engineering, Fatorda- Goa Page 1


Laboratory Manual (Operating System)
LABORATORY SAFETY INFORMATION

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.

ELECTRICAL SHOCK:Avoid contact with conductors in energized electrical


circuits.Electrocution has been reported at de voltages as low as 42 volts. Just 100 mA of current
passing through the chest is usually fatal. Muscle contractions can prevent the person from moving
away while being electrocuted. Do not touch someone who is being shocked while still in contact
with the electrical conductor or you may also be electrocuted. Instead, turn OFF the main MCB
(Red Color). This shuts off all power, except the lights. Make sure your hands are dry. The
resistance of dry, unbroken skin is relatively high and thus reduces the risk of shock. Skin that is
broken, wet or damp with sweat has a low resistance. When working with an energized circuit,
work with only your right hand, keeping your left hand away from all conductive material. This
reduces the likelihood of an accident that results in current passing through your heart. Be cautious
of rings, watches, and necklaces. Skin beneath a ring or watch is damp, lowering the skin
resistance. Shoes covering the feet are much safer than sandals. If the victim isn't breathing, find
someone certified in CPR. Be quick! Some of the staff in the Department Office are certified in
CPR (Mr. AvertanoBaretto- ). If the victim is unconscious or needs an ambulance, contact the
Department Office for help or call 108. If able, the victim should go to the Student Health Services
for examination and treatment.

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.

Don Bosco College of Engineering, Fatorda- Goa Page 2


Laboratory Manual (Operating System)
INSTRUCTIONS
TYPE LABORATORY SPECIFIC EQUIPMENT OPERATION & SAFETY RELATED
INSTRUCTIONS

1. Do not switch off power supply directly


2. Do not use pend rives or any other external device in lab

GENERAL INSTRUCTIONS:

1. Maintain discipline in the laboratory at all times.


2. Enter your details in the Log-In register every time you come to the lab.
3. Eatables & water bottles are not allowed in the lab.
4. DO NOT get your bags in the lab. Leave it outside on the rack when entering the lab.
5. Take care of your personal belongings. The staff is not responsible for loss of personal
items.
6. Use of Mobile Phones is STRICTLY PROHIBHITED in the lab. Anyone caught using their
cell phone in the laboratory; it will be confiscated and handed over to the principal.
7. DO NOT litter in the lab. Pencil shavings must be thrown in the dustbin.
8. The laboratory manual is not to be taken out of the lab. Please DO NOT damage the
laboratory manual by writing on it and tearing the pages.
9. Taking photographs of the laboratory manuals is prohibited.
10. DO NOT scribble on the desk.
11. A Candidate is considered to have successfully fulfilled the requirement of a
semester, provided he/she submits to the department a certified file reporting the
experiments conducted during the semester.

Don Bosco College of Engineering, Fatorda- Goa Page 3


Laboratory Manual (Operating System)
GUIDELINES FOR LABORATORY FILE
The laboratory file is a record of all work pertaining to the experiment. This record should be
sufficiently complete so that you or anyone else of similar technical background can duplicate the
experiment and data by simply following your laboratory file. Descriptive headings should be used
to separate and identify the various parts of the experiment. Record data in chronological order. A
neat, organized and complete record of an experiment is just as important as the experimental work.

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.

5. Procedure: In general, lengthy explanations of procedures are unnecessary. Be brief. Short


commentaries alongside the corresponding data may be used. Keep in mind the fact that the
experiment must be reproducible from the information given in your file.

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.

Types of Operating Systems:-


1. Batch Operating System
This type of operating system do not interact with the computer directly. There is an operator which
takes similar jobs having same requirement and group them into batches. It is the responsibility of
operator to sort the jobs with similar needs.

Advantages of Batch Operating System:-


-It is very difficult to guess or know the time required by any job to complete.
-Processors of the batch systems knows how long the job would be when it is in queue
-Multiple users can share the batch systems
-The idle time batch system is very less
-It is easy to manage large work repeatedly in batch system.
Disadvantages of Batch Operating System:-
-The computer operators should be well known with batch systems
-Batch systems are hard to debug
-It is sometime costly.
-The other jobs will have to wait for an unknown time if any job fails.
Examples of Batch based Operating System: Payroll System, Bank Statements etc.
2. Time-Sharing Operating Systems
Each task has given some time to execute, so that all the tasks work smoothly. Each user gets time
of CPU as they use single system. These systems are also known as Multitasking Systems. The

Don Bosco College of Engineering, Fatorda- Goa Page 5


Laboratory Manual (Operating System)
task can be from single user or from different users also. The time that each task gets to execute is
called quantum. After this time interval is over OS switches over to next task.

Advantages of Time-Sharing OS:-


-Each task gets an equal opportunity
-Less chances of duplication of software
-CPU idle time can be reduce.
Disadvantages of Time-Sharing OS:-
-Reliability problem
-One must have to take care of security and integrity of user programs and data
-Data communication problem.
Examples of Time-Sharing OSs are: Multics, Unix etc.
3. Distributed Operating System
These types of operating system is a recent advancement in the world of computer technology and
are being widely accepted all-over the world and, that too, with a great pace. Various autonomous
interconnected computers communicate each other using ashared communication network.
Independent systems possess their own memory unit and CPU. These are referred as loosely coupled
systems or distributed systems. These systems processors differ in sizes and functions. The major
benefit of working with these types of operating system is that it is always possible that one user can
access the files or software which are not actually present on his system but on some other system
connected within this network i.e., remote access is enabled within the devices connected in that

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

Disadvantages of Distributed Operating System:-


-Failure of the main network will stop the entire communication
-To establish distributed systems the language which are used are not well defined yet
-These types of systems are not readily available as they are very expensive. Not only that the
underlying software is highly complex and not understood well yet
Examples of Distributed Operating System are- LOCUS etc.
4. Network Operating System
These systems runs on a server and providesthe capability to manage data, users, groups, security,
applications, and other networking functions. These type of operating systems allows shared access
of files, printers, security, applications, and other networking functions over a small private network.
One more important aspect of Network OperatingSystems is that all the users are well aware ofthe
underlying configuration, of all other users within the network, their individual connections etc. and
that’s why these computers are popularly known as tightly coupled systems.

Advantages of Network Operating System:-

-Highly stable centralized servers


-Security concerns are handled through servers
-New technologies and hardware up-gradation are easily integrated to the system
-Server access are possible remotely from different locations and types of systems

Disadvantages of Network Operating System:-

-Servers are costly


-User has to depend on central location for most operations
-Maintenance and updates are required regularly
Examples of Network Operating System are: Microsoft Windows Server 2003, Microsoft
Windows Server 2008, UNIX, Linux, Mac OS X, Novell NetWare, and BSD etc.

Don Bosco College of Engineering, Fatorda- Goa Page 7


Laboratory Manual (Operating System)
5. Real-Time Operating System
These types of OS serves the real-time systems. The time interval required to process and respond
to inputs is very small. This time interval is called response time.
Real-time systems are used when there are time requirements are very strict like missile systems,
air traffic control systems, robots etc.

Two types of Real-Time Operating System which are as follows:

Hard Real-Time Systems


These OSs are meant for the applications where time constraints are very strict and even the
shortest possible delay is not acceptable. These systems are built for saving life like automatic
parachutes or air bags which are required to be readily available in case of any accident. Virtual
memory is almost never found in these systems.
Soft Real-Time Systems
These OSs are for applications where for time-constraint is less strict.

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.

Don Bosco College of Engineering, Fatorda- Goa Page 8


Laboratory Manual (Operating System)
-Complex Algorithms: The algorithms are very complex and difficult for the designer to write on.
-Device driver and interrupt signals: It needs specific device drivers and interrupts signals to
response earliest to interrupts.
-Thread Priority: It is not good to set thread priority as these systems are very less prone to switching
tasks.
Examples of Real-Time Operating Systems are: Scientific experiments, medical imaging systems,
industrial control systems, weapon systems, robots, air traffic control systems, etc.

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.

Turn Around Time = Completion Time – 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.

Waiting Time = Turn Around Time – Burst Time

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.

Don Bosco College of Engineering, Fatorda- Goa Page 10


Laboratory Manual (Operating System)
For the above given processes, first P1 will be provided with the CPU resources,

• Hence, waiting time for P1 will be 0

• P1 requires 21ms for completion, hence waiting time for P2 will be 21ms

• Waiting time for process P3 will be execution time of P1 + execution time

forP2, which will be (21+3) = 24ms.

• For process P4 it will be the sum of execution times of P1, P2 and P3= 30ms

Algorithm

Step 1: Assign the process to ready queue.

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.

Step 4: Repeat the step 1 to 3 until ready queue is empty.

Step 5: Calculate Waiting time and Turnaround time of individual Process.

Step 6: Calculate Average waiting time and Average Turnaround time.

Step7: print Average waiting time and Average Turnaround time

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;

Don Bosco College of Engineering, Fatorda- Goa Page 11


Laboratory Manual (Operating System)
floatavg;
sn = newScanner(System.in)
System.out.print("\nEnter the number of processes : ");
intn = sn.nextInt();
for(inti=0;i<n;i++)
{
System.out.println();
System.out.print("Enter the process ID of process "+(i+1)+" :
"); id[i]=sn.nextInt();
System.out.print("Enter the burst time of process "+(i+1)+" :
"); btime[i]=sn.nextInt();
}
wtime[0]=0;
for(inti=1;i<n;i++)
{
wtime[i]=wtime[i-1]+btime[i-1];
total=total+wtime[i];
}
avg=(float)total/n;
System.out.println("\nProcess_ID\tBurst_time\tWait_time")
; for(inti=0;i<n;i++)
{
System.out.println(id[i]+"\t\t"+btime[i]+"\t\t"+wtime[i]);
}
System.out.println("\nTotal wait time: "+total+"\nAverage wait time: "+avg);
}

Don Bosco College of Engineering, Fatorda- Goa Page 12


Laboratory Manual (Operating System)
Sample Output

Enter the number of processes : 3

Enter the process ID of process 1 : 1


Enter the burst time of process 1 : 3
Enter the process ID of process 2 : 2
Enter the burst time of process 2 : 6
Enter the process ID of process 3 : 3
Enter the burst time of process 3 : 2

Process_ID Burst_time Wait_time


1 3 0
2 6 3
3 2 9

Total wait time: 12


Average wait time: 4.0

Conclusion: Successfully completed implementation of non preemptive FCFS process


scheduling algorithm

Don Bosco College of Engineering, Fatorda- Goa Page 13


Laboratory Manual (Operating System)
Experiment No 2b

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.

Don Bosco College of Engineering, Fatorda- Goa Page 14


Laboratory Manual (Operating System)
Step 2- Assign CPU according to next shortest CPU burst. If there is a tie between two processes

(i.e. two processes having same next CPU burst), apply FCFS algorithm.
Program:

importjava.util.*;

public class NPSJF {


public static void main(String args[])
{
Scanner sc = newScanner(System.in);

System.out.println ("enter no of process:");


intn = sc.nextInt();
intpid[] = new int[n];

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;

if(tot == n) // total no of process = completed process loop will be terminated break;


for(inti=0; i<n; i++)
{
/* If i'th process arrival time <= system time and its flag=0 and burst<min That process will be
executed first */
if((at[i] <= st) && (f[i] == 0) && (bt[i]<min))

Don Bosco College of Engineering, Fatorda- Goa Page 15


Laboratory Manual (Operating System)
{
min=bt[i];

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++;
}
}

System.out.println("\npid arrival brust complete turn waiting"); for(inti=0;i<n;i++)


{
avgwt+= wt[i];
avgta+= ta[i];
System.out.println(pid[i]+"\t"+at[i]+"\t"+bt[i]+"\t"+ct[i]+"\t"+ta[i]+"\t"+wt[i]);
}

System.out.println ("\naveragetat is "+ (float)(avgta/n)); System.out.println ("average wt is "+


(float)(avgwt/n)); sc.close();
}
}

Sample Output:

enter no of process:4

enter process 1 arrival time:0

enter process 1 brust time:7

enter process 2 arrival time:2


enter process 2 brust time:4

enter process 3 arrival time:4

Don Bosco College of Engineering, Fatorda- Goa Page 16


Laboratory Manual (Operating System)
enter process 3 brust time:1

enter process 4 arrival time:5


enter process 4 brust time:4

Pid ArrivalBrust Complete Turn Waiting


1 0 7 7 7 0
2 2 4 12 10 6
3 4 1 8 4 3
4 5 4 16 11 7

averagetat is 8.0

averagewt is 4.0

Conclusion: successfully completed study, design and implementation of non preemptive


SJFprocess scheduling algorithm.

Don Bosco College of Engineering, Fatorda- Goa Page 17


Laboratory Manual (Operating System)
Experiment No 3a

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.

Don Bosco College of Engineering, Fatorda- Goa Page 18


Laboratory Manual (Operating System)
Algorithm:

Implementation:

Step 1- Traverse until all process gets completely executed.

Step 1.1 - Find process with minimum remaining time at every single time lap.

Step 1.2 - Reduce its time by 1.

Step 1.3 - Check if its remaining time becomes 0

Step 1.4 - Increment the counter of process completion.

Step 1.5 - Completion time of current process = current_time +1;

Step 1.6 - Calculate waiting time for each completed process.

Step 1.7 - Increment time lap by one.

Step 2- Find waiting time and turnaround time and print the same.

Program:

importjava.util.*;

public class PSJF{


public static void main (String args[])
{
Scanner sc=newScanner(System.in);
System.out.println ("enter no of process:");
intn= sc.nextInt();
intpid[] = new int[n]; // it takespidof process
intat[] = new int[n]; // at means arrival time
intbt[] = new int[n]; //btmeans burst time
intct[] = new int[n]; //ctmeans complete time
intta[] = new int[n];//tameansturn around time
intwt[] = new int[n]; //wtmeans waiting time
intf[] = new
int[n]; // f means it is flag it checks process is completed or not
intk[]= new
int[n]; // it is also storesbrust time
inti, st=0, tot=0;
float avgwt=0,
avgta=0;

Don Bosco College of Engineering, Fatorda- Goa Page 19


Laboratory Manual (Operating System)
for(i=0;i<n;i++)
{
pid[i]= i+1;
System.out.println ("enter process " +(i+1)+ " arrival time:");
at[i]= sc.nextInt();
System.out.println("enter process " +(i+1)+ " burst time:");
bt[i]= sc.nextInt();
k[i]= bt[i];
f[i]= 0;
}

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];

Don Bosco College of Engineering, Fatorda- Goa Page 20


Laboratory Manual (Operating System)
avgta+= ta[i];
}

System.out.println("pid arrival burst complete turn waiting");


for(i=0;i<n;i++)
{
System.out.println(pid[i] +"\t"+ at[i]+"\t"+ k[i] +"\t"+ ct[i] +"\t"+ ta[i] +"\t"+ wt[i]);
}
System.out.println("\naveragetat is "+ (float)(avgta/n));
System.out.println("average wt is "+ (float)(avgwt/n));
sc.close();
}
}

Sample Output

enter no of process: 4

enter process 1 arrival time:0


enter process 1 burst time: 7
enter process 2 arrival time:2
enter process 2 burst time:4
enter process 3 arrival time:4
enter process 3 burst time:1
enter process 4 arrival time:5
enter process 4 burst time:4

pid Arrival Burst Complete Turn Waiting


1 0 7 16 16 9
2 2 4 7 5 1
3 4 1 5 1 0
4 5 4 11 6 2

averagetat is 7.0
averagewt is 3.0

Conclusion: successfully completed study, design and implementation of preemptive


SJFprocess scheduling algorithm

Don Bosco College of Engineering, Fatorda- Goa Page 21


Laboratory Manual (Operating System)
Experiment No 3b

Aim:To study and implement preemptive “Round Robin” process schedulingalgorithm.

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:

PROCECESS BURS TTIME


Process 1 14
Process 2 6
Process 3 4
Process 4 12
Process 5 5

Average waiting time: 24.8


Average turnaround time: 33.6

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++)
{

Don Bosco College of Engineering, Fatorda- Goa Page 23


Laboratory Manual (Operating System)
if((j!=i)&&(bt[j]!=0))
wt[j]+=bt[i];
}
bt[i]=0;
}
}
sum=0;
for(k=0;k<n;k++)
sum=sum+bt[k];
}
while(sum!=0);
for(i=0;i<n;i++)
tat[i]=wt[i]+a[i];
System.out.println("process\t\tBT\tWT\tTAT");
//System.out.println("process");
for(i=0;i<n;i++)
{
System.out.println("process"+(i+1)+"\t"+a[i]+"\t"+wt[i]+"\t"+tat[i]);
}
floatavg_wt=0;
floatavg_tat=0;
for(j=0;j<n;j++)
{
avg_wt+=wt[j];
}
for(j=0;j<n;j++)
{
avg_tat+=tat[j];
}
System.out.println("average waiting time "+(avg_wt/n)+"\n Average turn around
time"+(avg_tat/n));
}
}

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

Don Bosco College of Engineering, Fatorda- Goa Page 24


Laboratory Manual (Operating System)
Average turnaround time: 8.666667

pid arrival brust complete turn waiting


107770
2 2 4 12 10 6
341843
4 5 4 16 11 7

averagetat is 8.0

averagewt is 4.0

Conclusion:Round Robin process scheduling algorithm was successfully studied and


implemented

Don Bosco College of Engineering, Fatorda- Goa Page 25


Laboratory Manual (Operating System)
Experiment No 4

AIM: To study and implement Threads.

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.

Life cycle of a thread

Don Bosco College of Engineering, Fatorda- Goa Page 26


Laboratory Manual (Operating System)
Advantages of Thread over Process

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.

3. Effective Utilization of Multiprocessor system: If we have multiple threads in a single process,


then we can schedule multiple threads on multiple processor. This will make process execution
faster.

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.

5. Communication: Communication between multiple thread is easier as thread shares common


address space. while in process we have to follow some specific communication technique for
communication between two process.

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

Don Bosco College of Engineering, Fatorda- Goa Page 27


Laboratory Manual (Operating System)
Creating and Starting Threads
Creating a thread in Java is done like this:
Thread thread = new 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().

Here is an example of creating a Java Thread subclass:

public class MyThread extends Thread


{
public void run(){
System.out.println("MyThread running");
}
}

To create and start the above thread you can do like this:

MyThreadmyThread = new MyThread();


myTread.start();

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".

You can also create an anonymous subclass of Thread like this:

Thread thread = new Thread(){


public void run(){
System.out.println("Thread Running");
}
}

Don Bosco College of Engineering, Fatorda- Goa Page 28


Laboratory Manual (Operating System)
thread.start();

This example will print out the text "Thread running" once the run() method is executed by the
new thread.

Runnable Interface Implementation

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.

Here is a Java Runnable example:

public class MyRunnable implements Runnable


{
public void run()
{
System.out.println("MyRunnable running");
}
}

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:

Thread thread = new Thread(new MyRunnable());


thread.start();

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".

You can also create an anonymous implementation of Runnable, like this:

Runnable myRunnable = new Runnable()


{
public void run()
{
System.out.println("Runnable running");
}
}
Thread thread = new Thread(myRunnable);
thread.start()

Program:

Don Bosco College of Engineering, Fatorda- Goa Page 29


Laboratory Manual (Operating System)
i. Runnable Class Example
packagecom.myjava.threads;
classMyRunnableThread implements Runnable{
public static intmyCount = 0;
publicMyRunnableThread()
{
}
public void run()
{
while(MyRunnableThread.myCount<= 10){
try
{
System.out.println("Expt Thread: "+(++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedExceptioniex) {
System.out.println("Exception in thread: "+iex.getMessage());
}
}
}
}
public class RunMyThread {
public static void main(String a[]){
System.out.println("Starting Main Thread...");
MyRunnableThreadmrt = new MyRunnableThread();
Thread t = new Thread(mrt);
t.start();
while(MyRunnableThread.myCount<= 10)
{
try{
System.out.println("Main Thread: "+(++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedExceptioniex){
System.out.println("Exception in main thread: "+iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}
OUTPUT:
Starting Main Thread...
Main Thread: 1
Expt Thread: 2
Main Thread: 3
Expt Thread: 4
Expt Thread: 5
Main Thread: 6
Don Bosco College of Engineering, Fatorda- Goa Page 30
Laboratory Manual (Operating System)
Main Thread: 8
Expt Thread: 7
Expt Thread: 9
Main Thread: 10
Expt Thread: 11
End of Main Thread...
BUILD SUCCESSFUL (total time: 1 second)

ii. Thread Class Example


packagecom.myjava.threads;
classMySmpThread extends Thread{
public static intmyCount = 0;
public void run(){
while(MySmpThread.myCount<= 10)
{
try{
System.out.println("Expt Thread: "+(++MySmpThread.myCount));
Thread.sleep(100);
}
catch (InterruptedExceptioniex)
{
System.out.println("Exception in thread: "+iex.getMessage());
}
}
}
}
public class RunThread
{
public static void main(String a[]){
System.out.println("Starting Main Thread...");
MySmpThreadmst = new MySmpThread();
mst.start();
while(MySmpThread.myCount<= 10)
{
try{
System.out.println("Main Thread: "+(++MySmpThread.myCount));
Thread.sleep(100);
}
catch (InterruptedExceptioniex)
{
System.out.println("Exception in main thread: "+iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}

Don Bosco College of Engineering, Fatorda- Goa Page 31


Laboratory Manual (Operating System)
OUTPUT:
Starting Main Thread...
Main Thread: 1
Expt Thread: 2
Expt Thread: 3
Main Thread: 3
Expt Thread: 4
Main Thread: 4
Expt Thread: 5
Main Thread: 5
Expt Thread: 6
Main Thread: 7
Main Thread: 8
Expt Thread: 9
Expt Thread: 10
Main Thread: 11
End of Main Thread...
BUILD SUCCESSFUL (total time: 2 seconds)

CONCLUSION:The study,design and implementation of Threads completed successfully.

Experiment No. 5

Don Bosco College of Engineering, Fatorda- Goa Page 32


Laboratory Manual (Operating System)
AIM: To study and implement system call.

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.

Functions of system call

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.

fwrite() : This function is used to write data to a stream

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.

Don Bosco College of Engineering, Fatorda- Goa Page 33


Laboratory Manual (Operating System)
opendir() : This function opens a directory stream

readdir() : This function reads the directory which is opened as a stream

atoi() : This function converts ascii argument to integer.

How to display login using “W” command?

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]

w command output / header:


The w command shows the following information about each user and their process on the syste
m:
USER – User name.
TTY – Terminal type such as pts/0 or console.
FROM – The remote host name or IP address.
LOGIN@ – Login time.
IDLE – Idel time.
JCPU – The JCPU time is the time used by all processes attached to the tty.
PCPU – The PCPU time is the time used by the current process displayed in WHAT field.
WHAT – The command line of USER’s current process.

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.

Don Bosco College of Engineering, Fatorda- Goa Page 34


Laboratory Manual (Operating System)
Normally when we try to view these files using cat command or vi editor they used to throw som
e junk characters and garbage values or in encrypted form or hex values. The output of these files
when open with vi or cat command are shown below to show how wtmp file look when opened
with vi.

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:

Don Bosco College of Engineering, Fatorda- Goa Page 35


Laboratory Manual (Operating System)
ii. System call using fork()
#include <stdio.h>
//#include <iostream.h>
#include <string.h>
// Required by for routine
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
main()
{
intpid;

pid = fork();

if (pid< 0) { // error occurred


fprintf(stderr, "Fork failed!\n");
exit(-1);
}else if (pid == 0) { // child process
printf("I am the child, return from fork=%d\n", pid);
execlp("/bin/ls", "lss", NULL);
}else { // parent process
printf("I am the parent, return from fork, child pid=%d\n", pid);
printf("Parent exiting!\n");
exit(0);
}
}

Don Bosco College of Engineering, Fatorda- Goa Page 36


Laboratory Manual (Operating System)
OUTPUT:

CONCLUSION:System calls for fork and all logged was studied and implemented successfully.

Experiment No. 6

Don Bosco College of Engineering, Fatorda- Goa Page 37


Laboratory Manual (Operating System)
Aim: To study and implement solution for dining philosopher problem using semaphores

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

Don Bosco College of Engineering, Fatorda- Goa Page 38


Laboratory Manual (Operating System)
control the behavior of each philosopher. But, semaphores can result in deadlock due to
programming errors.
Algorithm:
Each philosopher is represented by the following Algorithm:
rocess P[i]
while true do
{ THINK;
PICKUP(CHOPSTICK[i], CHOPSTICK[i+1 mod 5]);
EAT;
PUTDOWN(CHOPSTICK[i], CHOPSTICK[i+1 mod 5])
} //Above process is used parallel by all philosophers
Program:
packagedbce;
importjava.util.concurrent.Semaphore;
importjava.util.concurrent.ThreadLocalRandom;
public class DiningPhilosophers {
staticintphilosophersNumber = 5;
static Philosopher philosophers[] = new Philosopher[philosophersNumber];
static Fork forks[] = new Fork[philosophersNumber];
static class Fork {
public Semaphore mutex = new Semaphore(1);
void grab() {
try {
mutex.acquire(); }
catch (Exception e) {
e.printStackTrace(System.out);
}
}

void release() {
mutex.release();
}
booleanisFree() {
returnmutex.availablePermits() > 0;
}
}

static class Philosopher extends Thread {


publicint number;
public Fork leftFork;
public Fork rightFork;
Philosopher(intnum, Fork left, Fork right) {
number = num;
leftFork = left;
rightFork = right;

Don Bosco College of Engineering, Fatorda- Goa Page 39


Laboratory Manual (Operating System)
}
public void run(){
System.out.println("Hi! I'm philosopher #" + number);

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);
}
}
}

public static void main(String argv[]) {


System.out.println("Dining philosophers problem.");
for (int i = 0; i <philosophersNumber; i++) {
forks[i] = new Fork();
}
for (int i = 0; i <philosophersNumber; i++) {
philosophers[i] = new Philosopher(i, forks[i], forks[(i + 1) % philosophersNumber]);
philosophers[i].start();
}

while (true) {
try {
// sleep 1 sec
Thread.sleep(1000);
// check for deadlock
boolean deadlock = true;
for (Fork f : forks) {

Don Bosco College of Engineering, Fatorda- Goa Page 40


Laboratory Manual (Operating System)
if (f.isFree()) {
deadlock = false;
break;
}
}
if (deadlock) {
Thread.sleep(1000);
System.out.println("Hurray! There is a deadlock!");
break;
}
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
System.out.println("Bye!");
System.exit(0);
}
}

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.

Don Bosco College of Engineering, Fatorda- Goa Page 41


Laboratory Manual (Operating System)
Philosopher #0 grabs left fork.
Philosopher #4 releases right fork.
Philosopher #4 grabs left fork.
Philosopher #2 releases left fork.
Philosopher #1 grabs right fork.
Philosopher # eats for 649
Philosopher #3 grabs left fork.
Philosopher #2 releases right fork.
Hurray! There is a deadlock!
Bye!
BUILD SUCCESSFUL (total time: 2 seconds)

Conclusion: Successfully completed study and implementation of dining philosophers problem


using semaphore.

Experiment No. 7
Aim:To implement deadlock avoidance scheme using banker’s algorithm.
Requirements:

Don Bosco College of Engineering, Fatorda- Goa Page 42


Laboratory Manual (Operating System)
Software requirements: Windows Operating system, Net beans, JDK 7 or above
Hardware requirements: Personal/Desktop computer

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.

Available[ j ] = k means there are ‘k’ instances of resource type Rj

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.

Allocation[i, j ] = k means process Pi is currently allocated ‘k’ instances of resource type Rj

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

Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]

Banker’s algorithm consist of 1) Safety algorithm and 2) Resource request algorithm


Resource-Request Algorithm

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.

Don Bosco College of Engineering, Fatorda- Goa Page 43


Laboratory Manual (Operating System)
2) If Requesti<= Available Goto step (3); otherwise, Pi must wait, since the resources are not
available.

3) Have the system pretend to have allocated the requested resources to process Pi by modifying
the state as follows:

Available = Available – Requesti


Allocationi = Allocationi + Requesti
Needi = Needi– Requesti

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;

private void input()


{
Scanner sc=new Scanner(System.in);
System.out.print("Enter no. of processes and resources : ");
np=sc.nextInt(); //no. of process
nr=sc.nextInt(); //no. of resources
need=new int[np][nr]; //initializing arrays
max=new int[np][nr];
allocate=new int[np][nr];
avail=new int[1][nr];

System.out.println("Enter allocation matrix -->");


for(int i=0;i<np;i++)
for(int j=0;j<nr;j++)

Don Bosco College of Engineering, Fatorda- Goa Page 44


Laboratory Manual (Operating System)
allocate[i][j]=sc.nextInt(); //allocation matrix

System.out.println("Enter max matrix -->");


for(int i=0;i<np;i++)
for(int j=0;j<nr;j++)

max[i][j]=sc.nextInt(); //max matrix

System.out.println("Enter available matrix -->");


for(int j=0;j<nr;j++)

avail[0][j]=sc.nextInt(); //available matrix

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;
}

public void isSafe()


{
input();
calc_need();
booleandone[]=new boolean[np];
int j=0;

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

Don Bosco College of Engineering, Fatorda- Goa Page 45


Laboratory Manual (Operating System)
for(int k=0;k<nr;k++)
avail[0][k]=avail[0][k]-need[i][k]+max[i][k];
System.out.println("Allocated process : "+i);
allocated=done[i]=true;
j++;
}

if(!allocated) break; //if no allocation


}
if(j==np) //if all processes are allocated
System.out.println("\nSafely allocated");
else
System.out.println("All proceesscant be allocated safely");
}
public static void main(String args[]){
BankersAlgo b = new BankersAlgo();
b.isSafe();
}
}

OUTPUT:

Enter no. of processes and resources : 3 3


Enter allocation matrix -->
412
151
123
Enter max matrix -->
102
031
102
Enter available matrix -->
220
Allocated process : 0
Allocated process : 1
Allocated process : 2

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)

Don Bosco College of Engineering, Fatorda- Goa Page 46


Laboratory Manual (Operating System)
Requirements:
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer

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.

Following are the three basic page replacement algorithms:

• 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

Don Bosco College of Engineering, Fatorda- Goa Page 47


Laboratory Manual (Operating System)
Step 4: Now the new page is inserted at the tail of the queue
Step 5: Create a stack
Step 6: When the page fault occurs replace page present at the bottom of the stack
Step 7: Stop

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++;
}

Don Bosco College of Engineering, Fatorda- Goa Page 48


Laboratory Manual (Operating System)
// Store the recently used index of
// each page
indexes.put(pages[i], i);
}
// If the set is full then need to perform lru
// i.e. remove the least recently used page
// and insert the current page
else {
// Check if current page is not already
// present in the set
if (!s.contains(pages[i])) {
// Find the least recently used pages
// that is present in the set
intlru = Integer.MAX_VALUE, val=Integer.MIN_VALUE;
Iterator<Integer>itr = s.iterator();
while (itr.hasNext()) {
int temp = itr.next();
if (indexes.get(temp) <lru)
{
lru = indexes.get(temp);
val = temp;
}
}
// Remove the indexes page
s.remove(val);
// insert the current page
s.add(pages[i]);
// Increment page faults
page_faults++;
}
// Update the current page index
indexes.put(pages[i], i);
}
}
returnpage_faults;
}
// Driver method

public static void main(String args[])


{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4};
int capacity = 3;
int x= pageFaults(pages, pages.length, capacity);

for(int i=0;i<pages.length; i++)


{

Don Bosco College of Engineering, Fatorda- Goa Page 49


Laboratory Manual (Operating System)
System.out.println("Number of page faults considering page sequence"+pages[i]);
}
System.out.println("\nand number of frames="+capacity+"\tis ="+x);
}
}

OUTPUT

Number of page faults considering page sequence :7


Number of page faults considering page sequence :0
Number of page faults considering page sequence :1
Number of page faults considering page sequence :2
Number of page faults considering page sequence :0
Number of page faults considering page sequence :3
Number of page faults considering page sequence :0
Number of page faults considering page sequence :4
and number of frames=3 is =6

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;

Don Bosco College of Engineering, Fatorda- Goa Page 50


Laboratory Manual (Operating System)
for(int j = 0; j < frames; j++) {
if(buffer[j] == referencepage[i]) {
search = j;
hit++;
break;
}
}
if(search == -1) {
buffer[pointer] = referencepage[i];
fault++;
pointer++;
if(pointer == frames)
pointer = 0;
}
for(int j = 0; j < frames; j++)
mem_layout[i][j] = buffer[j];
}
for(int i = 0; i< frames; i++) {
for(int j = 0; j <ref_len; j++)
System.out.printf("%3d ",mem_layout[j][i]);
System.out.println();
}
System.out.println("The number of Hits: " + hit);
System.out.println("Hit Ratio: " + (float)((float)hit/ref_len));
System.out.println("The number of Faults: " + fault);
}
}

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

The number of Hits: 3


Hit Ratio: 0.5
The number of Faults: 3

Don Bosco College of Engineering, Fatorda- Goa Page 51


Laboratory Manual (Operating System)
Conclusion: Page replacement policies like First-in-first (FIFO)-out and recently used(LRU)
was successfully studied and implemented.

Experiment No. 9a
Aim:To implement First Come First Serve Disk Scheduling Algorithm

Requirements:

Don Bosco College of Engineering, Fatorda- Goa Page 52


Laboratory Manual (Operating System)
Software requirements: Windows Operating system, Net beans , JDK 7 or above
Hardware requirements: Personal/Desktop computer

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

Don Bosco College of Engineering, Fatorda- Goa Page 53


Laboratory Manual (Operating System)
{
public static void main(String args[])
{
intn,i,hs,flag,total=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of cylinders");
n=sc.nextInt();
int c[]=new int[n];
inthm[]=new int[n];
System.out.println("Enter the cylinder no.");
for(i=0;i<n;i++)
c[i]=sc.nextInt();
System.out.println("enter head start");
hs=sc.nextInt();
flag=hs;
for(i=0;i<n;i++) {
if(c[i] > flag)
{
hm[i]=c[i]-flag;
flag = c[i];
System.out.println("position\t"+hm[i]);
}
else
{
hm[i]=flag-c[i];
flag=c[i];
System.out.println("position\t"+hm[i]);
}
}
for(i=0;i<n;i++)
total=total+hm[i];
System.out.println("The total no of cylinders traversed during disk movement is:"+ total);
}
}

OUTPUT:
Enter no of cylinders
6
Enter the cylinder no.

Don Bosco College of Engineering, Fatorda- Goa Page 54


Laboratory Manual (Operating System)
4 8 3 10 6 2
enter head start
10
position 6
position 4
position 5
position 7
position 4
position 4
The total no of cylinders traversed during disk movement is:30

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:

Don Bosco College of Engineering, Fatorda- Goa Page 55


Laboratory Manual (Operating System)
Consider the example given below:
Let initial position of head be considered at point 50. Considering the location points of the head
movement given below, let us try to understand the logic of SSTF algorithm.

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.

Program: SSTF Disk Scheduling


packagedbce;
class node {
// represent difference between
// head position and track number
int distance = 0;
// true if track has been accessed
boolean accessed = false;
}

Don Bosco College of Engineering, Fatorda- Goa Page 56


Laboratory Manual (Operating System)
public class SSTF {
// Calculates difference of each
// track number with the head position
public static void calculateDifference(int queue[], int head, node diff[])
{
for (int i = 0; i<diff.length; i++)
diff[i].distance = Math.abs(queue[i] - head);
}
// find unaccessed track
// which is at minimum distance from head
public static intfindMin(node diff[])
{
int index = -1, minimum = Integer.MAX_VALUE;
for (int i = 0; i<diff.length; i++) {
if (!diff[i].accessed && minimum > diff[i].distance) {
minimum = diff[i].distance;
index = i;
}
}
return index;
}
public static void shortestSeekTimeFirst(int request[], int head)
{
if (request.length == 0)
return;
// create array of objects of class node
node diff[] = new node[request.length];
// initialize array
for (int i = 0; i<diff.length; i++)
diff[i] = new node();
// count total number of seek operation
intseek_count = 0;
// stores sequence in which disk access is done
int[] seek_sequence = new int[request.length + 1];
for (int i = 0; i<request.length; i++) {
seek_sequence[i] = head;
calculateDifference(request, head, diff);
int index = findMin(diff);
diff[index].accessed = true;
// increase the total count
seek_count += diff[index].distance;
// accessed track is now new head
head = request[index];
}
// for last accessed track
seek_sequence[seek_sequence.length - 1] = head;

Don Bosco College of Engineering, Fatorda- Goa Page 57


Laboratory Manual (Operating System)
System.out.println("Total number of seek operations = "+ seek_count);
System.out.println("Seek Sequence is");
// print the sequence
for (int i = 0; i<seek_sequence.length; i++)
System.out.println(seek_sequence[i]);
}
public static void main(String[] args)
{ // request array
intarr[] = {48, 60, 92, 11};
shortestSeekTimeFirst(arr, 50);
}
}

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

Don Bosco College of Engineering, Fatorda- Goa Page 58


Laboratory Manual (Operating System)
Hardware requirements: Personal/Desktop computer

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.

Let us understand the steps in creating a Shell Script


1. Create a fileusing a vieditor(or any other editor). Name script file with extension .sh
2. Start the script with #! /bin/sh
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh
"#!" is an operator called shebang which directs the script to the interpreter location. So, if we
use"#! /bin/sh" the script gets directed to the bourne-shell.
A shell script comprises following elements –
 Shell Keywords – if, else, break etc.
 Shell commands – cd, ls, echo, pwd, touch etc.
 Functions
 Control flow – if..then..else, case and shell loops etc.

Why do we need shell scripts


There are many reasons to write shell scripts –
 To avoid repetitive work and automation
 System admins use shell scripting for routine backups
 System monitoring
 Adding new functionality to the shell etc.
Advantages of shell scripts
 The command and syntax are exactly the same as those directly entered in command line,
so programmer do not need to switch to entirely different syntax
 Writing shell scripts are much quicker
 Quick start
 Interactive debugging etc.
Disadvantages of shell scripts
 Prone to costly errors, a single mistake can change the command which might be harmful
Don Bosco College of Engineering, Fatorda- Goa Page 59
Laboratory Manual (Operating System)
 Slow execution speed
 Design flaws within the language syntax or implementation
 Not well suited for large and complex task
 Provide minimal data structure unlike other scripting languages. etc
 list of widely used UNIX Commands in shell scripting.
1) echo
echo is a built-in command in the bash and C shells that writes its arguments to standard
output.
The syntax for echo is
echo [option(s)] [string(s)]

Eg:echo This is a pen


2) case
The case statement saves going through a whole set of if ..then ..else statements.
The syntax for case is
case<word> in
<first pattern>)
<statements>
;;
<second pattern>)
<statements>
;;
*)
<default statements>
;;
esac

 list of system calls in UNIX.

1) touch

Usage: touch [OPTION]... FILE...

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.

Don Bosco College of Engineering, Fatorda- Goa Page 60


Laboratory Manual (Operating System)
2) lspci
lspci is a command on Unix-like operating systems that prints ("lists") detailed
information about all PCI buses and devices in the system
Usage: lspci [<switches>]

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

echo "1.Create File :";


echo "2.Rename a File :";
echo "3.Delete File :";
echo "4.Exit";

echo "Enter your choice : ";

readch;
case $ch in
1)

echo " Please enter File name : ";


read filename;

if [ -f $filename ];
then
echo"File already existing"
else
touch $filename;
echo "File created "
ls -t | head -n 15
fi # end of if statement

Don Bosco College of Engineering, Fatorda- Goa Page 62


Laboratory Manual (Operating System)
;; # to break first switch case
2)
echo "Enter the name of a file to be rename : ";
readoldfile;
echo "Enter the new file name to be assign : ";
readnewfile;
mv $oldfile $newfile;

echo "File successfully renamed";

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

-r--r--r-- 1 rahulrahul 775 Oct 11 20:53 A-1.sh

rahul@rahulUbuntu:~/Desktop/Scripts/output$ chmod 744 A-1.sh


rahul@rahulUbuntu:~/Desktop/Scripts/output$ ls -l
total 8
-rwxr--r-- 1 rahulrahul 775 Oct 11 20:53 A-1.sh
rahul@rahulUbuntu:~/Desktop/Scripts/output$ ./A-1.sh

1.Create File :
2.Rename a File :
3.Delete File :
4.Exit

Don Bosco College of Engineering, Fatorda- Goa Page 63


Laboratory Manual (Operating System)
Enter your choice :
1
Please enter File name :
test
File created
test
A-1.sh
1.Create File :
2.Rename a File :
3.Delete File :
4.Exit

Enter your choice :


2

Enter the name of a file to be rename :


test
Enter the new file name to be assign :
successfull
File successfully renamed
successfull
A-1.sh

1.Create File :
2.Rename a File :
3.Delete File :
4.Exit

Enter your choice :


3

Enter the file name to be delete:


successfull

After deleting file:


A-1.sh
1.Create File :
2.Rename a File :
3.Delete File :
4.Exit

Enter your choice :


4

Exit from program

Don Bosco College of Engineering, Fatorda- Goa Page 64


Laboratory Manual (Operating System)
PROGRAM 2:
while true

do

echo "1.Display all terminal devices:";


echo "2.Display memory map :";
echo "3.Display processor information :";
echo "4.Exit";

echo "Enter your choice : ";

readch;
case $ch in
1)

echo "All terminal devices : ";


lspci
;; # to break first switch case

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:

Don Bosco College of Engineering, Fatorda- Goa Page 65


Laboratory Manual (Operating System)
PROGRAM 3:
while true

Don Bosco College of Engineering, Fatorda- Goa Page 66


Laboratory Manual (Operating System)
do

echo "1.Create directory :";


echo "2.delete directory :";
echo "3.change the directory";
echo "4. pwd";
echo "5.Exit";

echo "Enter your choice : ";

readch;
case $ch in
1)

echo "Please enter Directory name : ";


readdir;

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)

Don Bosco College of Engineering, Fatorda- Goa Page 67


Laboratory Manual (Operating System)
exit;
;;

OUTPUT:
rahul@rahulUbuntu:~/Desktop/Scripts/output$ ./A-4.sh
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit

Enter your choice :


1
Please enter Directory name :
new
Directory created
new
A-4.sh

1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
Enter your choice :
4

Current Working Directory :


/home/rahul/Desktop/Scripts/output

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

Don Bosco College of Engineering, Fatorda- Goa Page 68


Laboratory Manual (Operating System)
Enter your choice :
3
Changing current working directory to : enter the path
..
/home/rahul/Desktop/Scripts/output
5930561 A-4.sh 6573447 new

1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit

Enter your choice :


2
Enter the Directory name to be delete :
new
Directory Deleted successfully
A-4.sh
1.Create directory :
2.delete directory :
3.change the directory
4. pwd
5.Exit
Enter your choice :
5

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";

echo "Enter your choice : ";


readch;
case $ch in
1)
echo " Operating System Name : ";
uname
;; # to break first switch case
2)
echo "Operating System Version : ";
cat /proc/version

Don Bosco College of Engineering, Fatorda- Goa Page 69


Laboratory Manual (Operating System)
;;
3)
echo "Login Name : ";
who
;;
4)
echo "Host Name :"
hostname
;;
5)
echo "exit from program "
exit;
;;
esac # end of switch case
done

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

Operating System Name :


Linux

1.Display Operating System name :


2.Display Operating System Version:
3.Display Login name :
4.Display Hostname :
5.Exit
Enter your choice :
2

Operating System Version :


Linux version 4.15.0-36-generic (buildd@lgw01-amd64-031) (gcc version 7.3.0 (Ubuntu 7.3.0-
16ubuntu3)) #39-Ubuntu SMP Mon Sep 24 16:19:09 UTC 2018

1.Display Operating System name :


2.Display Operating System Version:
3.Display Login name :
4.Display Hostname :
5.Exit

Don Bosco College of Engineering, Fatorda- Goa Page 70


Laboratory Manual (Operating System)
Enter your choice :
3
Login Name :
rahul :0 2018-10-18 17:09 (:0)
1.Display Operating System name :
2.Display Operating System Version:
3.Display Login name :
4.Display Hostname :
5.Exit
Enter your choice :
4

Host Name :
rahulUbuntu

1.Display Operating System name :


2.Display Operating System Version:
3.Display Login name :
4.Display Hostname :
5.Exit
Enter your choice :
5
Exit from program

Conclusion: Shell scripting was successfully completed with implementation of few operating
system information related scripts.

Don Bosco College of Engineering, Fatorda- Goa Page 71


Laboratory Manual (Operating System)

You might also like