0% found this document useful (0 votes)
15 views

Operating System Lab File (1)

The document is a practical lab file for a B.Tech course in Operating Systems at I.K. Gujral Punjab Technical University. It includes various experiments such as the installation of operating systems, implementation of CPU scheduling algorithms, shell programming, and virtualization using VirtualBox. Each experiment outlines objectives, theoretical background, and step-by-step procedures for completion.

Uploaded by

gulshankr843402
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Operating System Lab File (1)

The document is a practical lab file for a B.Tech course in Operating Systems at I.K. Gujral Punjab Technical University. It includes various experiments such as the installation of operating systems, implementation of CPU scheduling algorithms, shell programming, and virtualization using VirtualBox. Each experiment outlines objectives, theoretical background, and step-by-step procedures for completion.

Uploaded by

gulshankr843402
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Operating System LAB FILE

B. Tech (I. K. Gujral Punjab Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by GULSHAN KUMAR 1149
Department of Computer Science & Engineering

Practical File

SUBJECT: OPERATING SYSTEMS LAB

[BTCS404-18]

B.Tech – 4th Semester

[Batch 2021-25]

Rayat Bahra Institutions of Engineering


And Nano-Technology Hoshiarpur.

Submitted To: Submitted By:


Ms. Navneet Kaur Sahil- 2106672

0 1149
Downloaded by GULSHAN KUMAR
Index

S. No. Name of Practical Date Remark

1. Installation Process of various operating systems

2. Implementation of CPU scheduling algorithms to find turnaround


time and waiting time. a) FCFS b) SJF c) Round Robin (pre-emptive)
d) Priority
3. Virtualization, Installation of Virtual Machine Software and
installation of Operating System on Virtual Machine

4. Commands for files & directories: cd, ls, cp, md, rm, mkdir, rmdir.
Creating and viewing files using cat. File comparisons. Disk related
commands: checking disk free spaces. Processes in linux, connecting
processes with pipes, background processing, managing multiple
processes. Background process: changing process priority,
scheduling of processes at command, batch commands, kill, ps, who,
sleep. Printing commands, grep, fgrep, find, sort, cal, banner, touch,
file. File
related commands ws, sat, cut, grep.
5. Shell Programming: Basic of shell programming, various types of
shell, Shell Programming in bash, conditional & looping statement,
case statements, parameter passing and arguments, shell variables,
shell keywords, creating shell programs for automate system tasks,
report printing
6. Implementation of Bankers algorithm for the purpose of deadlock
avoidance

Downloaded by GULSHAN KUMAR 1149


EXPERIMENT – 1

AIM: Installation Process of various operating systems.

THEORY: OPERATING SYSTEM:


An operating system (OS) is a collection of software that manages computer
hardware resources and provides common services for compute programs. The
operating system is an essential component of the system software in a computer
system. Application programs usually require an operating system to function.

EXAMPLES: Five of the most common operating systems are Microsoft


Windows, Apple macOS, Linux, Android and Apple's iOS.

How to Install Linux operating system step by step procedure.

Install Linux Using Virtual Box VMWARE


In this way, nothing will affect your Windows operating system.

What Are Requirements?

 Good internet connection

 At least 4GB RAM

 At least 12GB of free space

Steps:
1. Download the VIRTUAL BOX from original ORACLE VIRTUAL BOX

site. You can refer below link

https://www.virtualbox.org/

Downloaded by GULSHAN KUMAR 1149


2. Install Linux Using Virtual Box

Use the .iso file or ISO file that can be downloaded from the internet and start the

virtual box.

Downloaded by GULSHAN KUMAR 1149


Here we need to allocate RAM to virtual OS. It should be 2 GB as per minimum

requirement.

 Choose an option under Create a virtual disk.

Downloaded by GULSHAN KUMAR 1149


 Choose a type of storage on physical hard disk. And choose the disk

size(min 12 GB as per requirement)

 Click on create option and then click on the START button to start the

virtual box and browse to the location of the .iso file of the OS.

Downloaded by GULSHAN KUMAR 1149


 Now Linux OS will start, Click on install option.

Downloaded by GULSHAN KUMAR 1149


 Select the drive for completing the OS installation. Select “Erase Disk and

install Ubuntu” in case you want to replace the existing OS otherwise select

“Something else” option and click INSTALL NOW.

Downloaded by GULSHAN KUMAR 1149


 Click on Continue.

 Choose a username and password.

Downloaded by GULSHAN KUMAR 1149


You are almost done. It should take 10-15 minutes to complete the installation.

Once the installation finishes, restart the system.

NOTE: In case of any issue close and again start the virtual box.

The Linux operating systems now offer millions of programs/applications to

choose from, most of them free to install! Linux is also the OS of choice for Server

environments due to its stability and reliability (Mega-companies like Amazon,

Facebook, and Google use Linux for their Servers). It proves to be a good choice

for everyone.

Downloaded by GULSHAN KUMAR 1149


EXPERIMENT-2

AIM: Implementation of CPU scheduling algorithms to find turnaround time and


waiting time. a) FCFS b) SJF c) Round Robin (pre-emptive) d) Priority

(a) Implementation FCFS-


#include<iostream>
using namespace std;
void findWaitingTime(int processes[], int n, int bt[], int wt[])
{
wt[0] = 0;
for (int i = 1; i< n ; i++ )
{
wt[i] = bt[i-1] + wt[i-1] ;}
}
void findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[])
{
for (int i = 0; i< n ; i++)
{
tat[i] = bt[i] + wt[i];}
}
void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, bt, wt);
findTurnAroundTime(processes, n, bt, wt, tat);
cout<< "Processes "<< " Burst time " << " Waiting time " << " Turn around
time\n";
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout<< " " << i+1 << "\t\t" <<bt[i] <<"\t "<<wt[i] <<"\t\t " << tat[i] <<endl;
}
cout<< "Average waiting time = " << (float)total_wt / (float)n;
cout<< "\nAverageturn around time = "<< (float)total_tat / (float)n;
}
int main()

10

Downloaded by GULSHAN KUMAR 1149


{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
int burst_time[] = {10, 5, 8};
findavgTime(processes, n, burst_time);
return 0;
}

(b) Implementation SJF

#include <bits/stdc++.h>
using namespace std;
struct Process {
int pid;
int bt;
int art;
};
void findTurnAroundTime(Process proc[], int n, int wt[], int tat[])
{ for (int i = 0; i < n; i++)
tat[i] = proc[i].bt + wt[i];
}
void findWaitingTime(Process proc[], int n, int wt[]) {
int rt[n];
for (int i = 0; i < n; i++)
rt[i] = proc[i].bt;
int complete = 0, t = 0, minm = INT_MAX;
int shortest = 0, finish_time;
bool check = false;

11

Downloaded by GULSHAN KUMAR 1149


while (complete != n)
{ for (int j = 0; j < n; j++)
{
if ((proc[j].art <= t) && (rt[j] < minm) && rt[j] > 0)
{ minm = rt[j];
shortest = j;
check = true;
}
}
if (check == false) {
t++;
continue;
}
rt[shortest]--;
minm = rt[shortest];
if (minm == 0)
minm = INT_MAX;
if (rt[shortest] == 0) {
complete++;
check = false;
finish_time = t + 1;
wt[shortest] = finish_time -
proc[shortest].bt -
proc[shortest].art;
if (wt[shortest] < 0)
wt[shortest] = 0;
} t+
+;
}
}
void findavgTime(Process proc[], int n)
{ int wt[n], tat[n], total_wt = 0,
total_tat = 0;
findWaitingTime(proc, n, wt);
findTurnAroundTime(proc, n, wt, tat);
cout << "Processes " << " Burst time " << " Waiting time " << " Turn around
time\n";
for (int i = 0; i < n; i++)
{ total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];

12

Downloaded by GULSHAN KUMAR 1149


cout << " " << proc[i].pid << "\t\t" << proc[i].bt << "\t\t " << wt[i] << "\t\t "
<< tat[i] << endl;
}
cout << "\nAverage waiting time = " << (float)total_wt / (float)n; cout << "\
nAverage turn around time = " << (float)total_tat / (float)n;
}
int main() {
Process proc[] = { { 1, 5, 1 }, { 2, 3, 1 }, { 3, 6, 2 }, { 4, 5, 3 } };
int n = sizeof(proc) / sizeof(proc[0]);
findavgTime(proc, n);
return 0;
}

(c) Implementation of Round Robin-


#include<iostream>
using namespace std;
void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum)
{ int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];
int t = 0;
while (1)
{ bool done = true;
for (int i = 0 ; i < n; i++)
{ if (rem_bt[i] > 0)
{ done = false;
if (rem_bt[i] > quantum)

13

Downloaded by GULSHAN KUMAR 1149


{ t += quantum;
rem_bt[i] -= quantum; }
else
{ t = t + rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0; }
}
}
if (done == true)
break; }
}
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{ for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i]; }
void findavgTime(int processes[], int n, int bt[], int quantum)
{ int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, bt, wt, quantum);
findTurnAroundTime(processes, n, bt, wt, tat);
cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";
for (int i=0; i<n; i++)
{ total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "<< wt[i] <<"\t\t " << tat[i] <<endl;
}
cout << "Average waiting time = "<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "<< (float)total_tat / (float)n; }
int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
int burst_time[] = {10, 5, 8};
int quantum = 2; cout<<"Quantum="<<quantum<<"\
n"; findavgTime(processes, n, burst_time, quantum);
return 0;
}

14

Downloaded by GULSHAN KUMAR 1149


(d) Implementation of Priority scheduling-
#include<bits/stdc++.h>
using namespace std;
struct Process {
int pid;
int bt;
int priority;
};
bool compare(Process a, Process b)
{ return (a.priority > b.priority);
}
void waitingtime(Process pro[], int n, int wt[])
{ wt[0] = 0;
for (int i = 1; i < n ; i++ )
wt[i] = pro[i-1].bt + wt[i-1] ;
}
void turnarround( Process pro[], int n, int wt[], int tat[])
{ for (int i = 0; i < n ; i++)
tat[i] = pro[i].bt + wt[i];
}
void avgtime(Process pro[], int n) {
int wt[n], tat[n], total_wt = 0, total_tat = 0;
waitingtime(pro, n, wt);
turnarround(pro, n, wt, tat);

15

Downloaded by GULSHAN KUMAR 1149


cout << "\nProcesses "<< " Burst time " << " Waiting time " << " Turn around
time\n";
for (int i=0; i<n; i++)
{ total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << pro[i].pid << "\t\t" << pro[i].bt << "\t " << wt[i] << "\t\t " <<
tat[i] <<endl;
}
cout << "\nAverage waiting time = " << (float)total_wt / (float)n;
cout << "\nAverage turn around time = " << (float)total_tat / (float)n;
}
void scheduling(Process pro[], int n)
{ sort(pro, pro + n, compare);
cout<< "Order in which processes gets executed \n";
for (int i = 0 ; i < n; i++)
cout << pro[i].pid <<" " ;
avgtime(pro, n);
}
int main() {
Process pro[] = {{1, 10, 2}, {2, 5, 0}, {3, 8, 1}};
int n = sizeof pro / sizeof pro[0];
scheduling(pro, n);
return 0;
}

16

Downloaded by GULSHAN KUMAR 1149


EXPERIMENT-3

AIM: Virtualization, Installation of Virtual Machine Software and installation of


Operating System on Virtual Machine.

Introduction
Virtual Box allows you to run an entire operating system inside another operating
system. Please be aware that you should have a minimum of 512 MB of RAM. 1
GB of RAM or more is recommended.

Comparison to Dual-Boot
Many websites (including the one you're reading) have tutorials on setting up dual-
boots between Windows and Ubuntu. A dual-boot allows you, at boot time, to
decide which operating system you want to use. Installing Ubuntu on a virtual
machine inside of Windows has a lot advantages over a dual-boot (but also a few
disadvantages).

Advantages of virtual installation

 The size of the installation doesn't have to be predetermined. It can be


a dynamically resized virtual hard drive.
 You do not need to reboot in order to switch between Ubuntu and Windows.
 The virtual machine will use your Windows internet connection, so you
don't have to worry about Ubuntu not detecting your wireless card, if
you have one.
 The virtual machine will set up its own video configuration, so you
don't have to worry about installing proprietary graphics drivers to get a
reasonable screen resolution.
 You always have Windows to fall back on in case there are any problems.
All you have to do is press the right Control key instead of rebooting your
entire computer.
 For troubleshooting purposes, you can easily take screenshots of any part of
Ubuntu (including the boot menu or the login screen).
 It's low commitment. If you later decide you don't like Ubuntu, all you
have to do is delete the virtual hard drive and uninstall VirtualBox.

Disadvantages of virtual installation

 In order to get any kind of decent performance, you need at least 512 MB
of RAM, because you are running an entire operating system (Ubuntu)
inside
17

Downloaded by GULSHAN KUMAR 1149


another entire operating system (Windows). The more memory, the better. I
would recommend at least 1 GB of RAM.
 Even though the low commitment factor can seem like an advantage at
first, if you later decide you want to switch to Ubuntu and ditch Windows
completely, you cannot simply delete your Windows partition. You would
have to find some way to migrate out your settings from the virtual
machine and then install Ubuntu over Windows outside the virtual
machine.
 Every time you want to use Ubuntu, you have to wait for two boot times
(the time it takes to boot Windows, and then the time it takes to boot Ubuntu
within Windows).

Installation Process
Step 1: The first thing you have to do is to install oracle VirtualBox. Install it the
same way you would any normal Windows program. Then get Ubuntu disk image
(.iso file).

Step 2: After you launch VirtualBox from the Windows Start menu, click on New
to create a new virtual machine. When the New Virtual Machine Wizard appears,
click Next.

18

Downloaded by GULSHAN KUMAR 1149


Step 3: You can call the machine whatever you want. If you're installing Ubuntu, it
makes sense to call it Ubuntu, I guess. You should also specify that the operating
system is Linux.

Step 4: VirtualBox will try to guess how much of your memory (or RAM) to
allocate for the virtual machine. If you have 1 GB or less of RAM, I would advise
you stick with the recommendation. If, however, you have over 1 GB, about a
quarter your RAM or less should be fine. For example, if you have 2 GB of RAM,
512 MB is fine to allocate. If you have 4 GB of RAM, 1 GB is fine to allocate. If
you have no idea what RAM is or how much of it you have, just go with the
default.

Click Next.

19

Downloaded by GULSHAN KUMAR 1149


Step 5: If this is your first time using VirtualBox (which it probably is if you need
a tutorial on how to use it), then you do want to Create new hard disk and then
click Next.

Step 6: Click Next again.

20

Downloaded by GULSHAN KUMAR 1149


Step 7: Theoretically, a dynamically expanding virtual hard drive is best, because
it'll take up only what you actually use. I have come upon weird situations, though,
when installing new software in a virtualized Ubuntu, in which the virtual hard
drive just fills up instead of expanding. So I would actually recommend picking a
Fixed-size storage.

Step 8: Ubuntu's default installation is less than 3 GB. If you plan on adding

21

Downloaded by GULSHAN KUMAR 1149


software or downloading large files in your virtualized Ubuntu, you should tack on
some buffer.

Step 9: Click Create and wait for the virtual hard drive to be created. This is
actually just a very large file that lives inside of your Windows installation.

22

Downloaded by GULSHAN KUMAR 1149


Step 10: The next thing to do to make the (currently blank) virtual hard drive
useful is to add the downloaded Ubuntu disk image (the .iso) boot on your virtual
machine. Click on Settings and Storage. Then, under CD/DVD Device, next to
Empty, you'll see a little folder icon. Click that.

Step 11:Select the Ubuntu .iso you downloaded earlier.

23

Downloaded by GULSHAN KUMAR 1149


Step 12: Once you've selected it, click OK.

Then double-click your virtual machine to start it up.

24

Downloaded by GULSHAN KUMAR 1149


Step 13: You may get a bunch of random warnings/instructions about how to
operate the guest operating system within VirtualBox. Read those, and then you
may also want to mark not to see those again.

Step 14: Wait for Ubuntu to boot up.

25

Downloaded by GULSHAN KUMAR 1149


Step 15: Once it's started up, just follow the regular installation procedure as if you
were installing.

26

Downloaded by GULSHAN KUMAR 1149


EXPERIMENT-4

AIM: Commands for files & directories: cd, ls, cp, md, rm, mkdir, rmdir. Creating
and viewing files using cat. File comparisons. Disk related commands: checking
disk free spaces. Processes in linux, connecting processes with pipes, background
processing, managing multiple processes. Background process: changing process
priority, scheduling of processes at command, batch commands, kill, ps, who,
sleep. Printing commands, grep, fgrep, find, sort, cal, banner, touch, file. File
related commands ws, sat, cut, grep.

OBJECTIVES: To study various linux commands

COMMAND EXECUTION :
To begin with, the kernel displays a shell prompt after authorized login. The shell
waits for the input from the user, decodes the command line and searches for the
program.
Terminal

If the program is found, the shell retrieves and submits it to the kernel to executes
the program. The kernel delivers the output. If the command is not found, it signals
the kernel to display command not found at the terminal. The shell accepts the
kernels reply, and in both cases displays thee next prompt. This once the shell
encounters end of input, it instructs the kernel to log out the user, and displays the
login message again. The system directories where the command file programs are
stored are the /bin and /usr/bin. On receipt of the command, which is nothing but

27

Downloaded by GULSHAN KUMAR 1149


the executable file names in the system directory, the shell locates them and
transfers control to the kernel to execute. These filenames can be verified by the
command pwd and ls, after changing to the directories /bin and /usr/bin.

CLASSIFICATION OF COMMANDS
User Access and User ID commands
Directory Commands
Editor Commands
File Manipulation commands
Security and Protection.
Inter-user and inter-machine communication commands
Information commands
Process Management commands
Program Development and Debugging commands
Text Processing commands
I/O Redirection and Piping
Shell commands and shell programming
Invoking command interpreters
System Administration commands for
Normal day-to-day administration
System monitoring
Installation and operation
Accounting
USER ACCESS AND USER ID COMMANDS
□ Login :
This command means to log in to the system. It is a process by which user
identifies himself to the system. The system prompts with a message : Login :
□ Logging off :
The new login message indicates that the session has been terminated thus making
it available for the next user. The exit command or ctrl+d means to logout the
system.
□ Password :
Set the user’s password or change the earlier login password. Password is a
sequence of letters and digits i.e. used to verify that user is allowed to use this user
id.
Syntax :- password:

DIRECTORY COMMANDS
 Mkdir :

28

Downloaded by GULSHAN KUMAR 1149


It is used to create directories. That is why as its syntax indicates
making of directories. Syntax: Mkdirdir
You can create a number of subdirectories with one mkdircommand. We can
also create a directory tree.
 Rmdir :

The rmdir command removes directories. The directory to be removed


should be empty. Syntax : Rmdirdir .When you remove a directory a
reverse logic is used.
 Cd :

This command is use to change the current directory.


Syntax : Cd dir
 Pwd :

Print or display the path of the present working directory. At anytime,


you should be able to know what your current directory. The special
directory logging into the system is called the home directory. Syntax: Pwd
 Ls :

List the file and subdirectories contained in a directory. Syntax: Ls dir


Switches :
 Ls –l : It provides a more detailed description of files in a dir.

 Ls –r : It provides listing in reverse order.

 Ls -x : it provides a multi-columnar output.

 Ls –a : it shows all filenames, hidden files, single or double dot files.

 Find :

It recursively examines, the list of files in a sub-directory to look for a


file attribute.
Syntax: Find <path list><selection criteria><selection>
It recursively examines all files in the subdirectories, then matches each file
for one or more selection criteria. Finally it takes some action on those
selected files.
Switches:
 –Name fname : selects file

 –Links +x : selects file if it has more then x links.

29

Downloaded by GULSHAN KUMAR 1149


 –User usname : selects file if it belongs to user usname.

 –Group gname :selects file, if it belongs to group gname.

 –Size +x[c] : selects the file, if size of file is greater then x blocks.

[c] is optional, it is for characters.

FILE MANIPULATION COMMANDS


 Cat :

To create a file, it is similar to copy con of DOS. CAT is also used for
displaying the contents of file.Syntax: CAT filename
The problem with CAT is, it shows only 24 line (one screen full). If
your file has 50 lines, then it shows last 24 lines leaving first 16 lines. So we
can usepg/more here to see whole file.
 Rm :

Remove a file or directory. Multiple files can also be removed at same


time.
Syntax : RM file1 file2
But for multiple file removal, all files must lie in same sub-directory.
 Sort :

It sorts and merges files. It sort lines on the main files, together and
writes the result on the standard output. The sort command bases its
comparison on or more keys, which is part of the data in the file i.e. used
to make comparisons for the sorting process. It normally sorts the input
file according to the ASCII collating sequence spaces, punctuations,
numbers, uppercase and lowercase letters.
Syntax : $ sort [options] filename
E.g: $ sort a.lst
OPTIONS :
-t :overwrites the default deleter.
-d : sorts the file alphabetically.
-r : inverse order.
-n : used when sorting numeric fields.
-o : redirect the output to a new file

SECURITY AND PROTECTION COMMANDS

 Chmod :

30

Downloaded by GULSHAN KUMAR 1149


To change mode of the system. It is used to set the three permissions
for all the three categories of users of the files. The owner of the file can
only use it.
Syntax: Chmod<category><operation><permission><filename(s)>
Categories Operation Permission
U – user + assign permissions R – read
permission
G – group - remove permissions W – write
permission
O – others = assign absolute X – execute permission
A - all

PROCESS MANAGEMENT COMMANDS


 Ps : PROCESS STATUS

It is used to display the attributes of a process. It has the knowledge of


the kernel built into it. It reads through the kernel data structures or
process tables to fetch the process characteristics. By default, pslists out
the processes associated with a user at that terminal. Syntax :- ps
Switches :-
-f :- doesnot provide ancestry of process.
-a :- lists out the processes of all users but doesnot display system process.
-u :- lets you know the activities of any user.
-e :- list every process which is active on system.
 Kill :

A process an be terminated prematurely by using killcommand.


Syntax :- kill 105 it terminates job with PID 105.

INFORMATION COMMANDS
 Date :

Tells the system to print the date and time.


Syntax: Date [MM ddhh mm[yy] ]
Switches:
 +%D : it shows date as mm/dd/yy.

 +%H: shows hours 00-23.

 +%M: minutes from 0-59.

31

Downloaded by GULSHAN KUMAR 1149


 Who :

It is use to get information about all users who are currently logged into
the system.
Syntax: Who
User name
 Who am i :

User or is getting information about himself.


Syntax: WHO AM I
 Echo :

It prints or echoes at the terminal whatever else user happens to type on


the line.
Syntax: Echo ‘any line’
 Exit :

This command is use to terminate a program. The command is


generally run with a numeric argument. Syntax: Exit
 Cal :

It comprehends and displays the entire calendar of any year from one
A.D to 9999 A.D. Syntax: $ Cal
Cal command displays the current date as well as the calendar (month
proceeding current month itself and month following the current month)
Syntax: $ Cal <month><year>
This syntax displays that month’s calendar only.

FILTER COMMANDS
A filter is a device that reads the standard and writes to the standard
output in a particular format. The format of the output depends on the
properties of the filter.
 GREP :

Grep is one of the most useful UNIX filters. It scans a file for the
occurrence of a pattern, and can display the selected pattern, the line numbers

32

Downloaded by GULSHAN KUMAR 1149


in which they are found, or the filenames where the pattern occurs. Grep can
also select lines containing the pattern.
Syntax : $ grep options patterns filename(s)
E.g. $ grep president emp.lst
OPTIONS :
-c (continuous occurrence) : the –c (count) options counts the
occurrences.
-n (displaying line numbers : the –n (number) option can be used to
display the line numbers containing the pattern, along the lines.
-v (deleting lines) : the –v (inverse) option selects all but the lines
containing the pattern.
 Cmp:

It is use to comparing two files. It uses two file names as arguments and
displays the difference on the terminal. Syntax: $ Cmp file1 file2
The two files are compared byte-by-byte and the location of the first
mismatch is echoed to the string.
Switches:
–l: list option gives a detailed list of byte number and differing bytes in
octal for each character that differ in both the files.
 Comm:

Compares two sorted files (ASCII collating sequence) and compares


each line of the first file with its corresponding line in the second file.
Displays the columnar outputs.
Syntax: $ Comm. file1 file2
 DIFF :

It is same as cmp. It displays file that consists and also tells which
time in one file have to be changed to make the two files identical. Syntax:
$ Diff file1 file2
Switches:
 –e: generates a script which when applied to first file will convert to
second.

 -b: causes trailing blanks to be ignored.

INTER USER & INTER MACHINE COMMANDS


 Finger : DETAILS OF USERS

33

Downloaded by GULSHAN KUMAR 1149


Like who, the finger command also lists login details of a user, but is
a more informative tool.
Syntax : $ finger
When used without arguments, it simply produces a list of all the
users logged on to the system. Unlike who, finger can also provide details
about a single user. This user is logged on to the same machine the
command is run on. It also runs in a network and it can obtain information
about remote users.

I/O REDIRECTION & PIPING COMMANDS


Redirection means the input to a command can be taken from a file other
than the user’s terminal keyboard. Similarly, output of command can be
written onto a disk file or onto the printer instead of the screen(VDU). Three
types of redirection in unix are :-
 > :- output to be stored in directed file not on the user’s terminal.

Syntax :- cat filename1 > filename2


Example:- cat test1 1 > test2 1 means output redirection.
 < :- input to be taken from the file .

syntax :- cat < filename


Example :- cat 0 < test 0 means input redirection.

 >> :- output to be appended to end of file content and not

overwrite. Syntax :- cat filename1 >> filename2


Example :- cat test1 >> test2

MISCELLANEOUS COMMANDS
Result:All Linux commands are implemented successfully.
 Outcome: Students will learn Ln :

Files are linked with ln comand with two filenames as arguments.


Syntax:- ln file1 file2
Eg:- ln mohitchiku
 TOUCH:

To create an empty file on disk.

34

Downloaded by GULSHAN KUMAR 1149


Syntax: $Touch filename
Touch command is use for following 3 purposes :
a. Creation time

b. Last access time

c. Last modification time

It is use to alter the access time, creation time and modification time.
Switches:
 –a : access time

 –c : creation time

 –m : modification time

If these switches are not there, it updates all the three.


 Uname :

You know your machine name by this command.


Syntax:- uname
Switches:-
-n :- machine name in network.
-a :- processor on which version exists.
-v :- version of unix.
 SLEEP:

This command puts the system to sleep for a specified number of


seconds.
Syntax: $ Sleep time
A shell prompt will appear only after the specified time.
Sleep command is used to retain the output of a particular command for a short
period of time before the screen displays the output of another command.

Result:All Linux are implemented successfully.


Outcome: Students will learn about the Linux commands and their uses.

35

Downloaded by GULSHAN KUMAR 1149


EXPERIMENT-5
AIM: Shell Programming: Basic of shell programming, various types of shell,
Shell Programming in bash, conditional & looping statement, case statements,
parameter passing and arguments, shell variables, shell keywords, creating shell
programs for automate system task, reporting printing.

THEORY: Usually shells are interactive that mean, they accept command as input
from users and execute them. However some time we want to execute a bunch of
commands routinely, so we have type in all commands each time in terminal.
As shell can also take commands as input from file we can write these commands
in a file and can execute them in shell to avoid this repetitive work. These files are
called Shell Scripts or Shell Programs.
When you login to a Unix system, a program called a shell process is run for you.
A shell process is a command interpreter that provides you with an interface to the
operating system. A shell script is just a file of commands, normally executed by a
shell process that was spawned to run the script.
vi Editor in UNIX
The default editor that comes with the UNIX operating system is called vi (visual
editor). Using vi editor, we can edit an existing file or create a new file from
scratch. We can also use this editor to just read a text file.
Syntax:
Vi filename
Input:

Output:

Modes of Operation in vi editor There are three modes of operation in vi:

Command Mode: When vi starts up, it is in Command Mode. This mode is where
vi interprets any characters we type as commands and thus does not display them
in the window. This mode allows us to move through a file, and to delete, copy, or
paste a piece of text.
To enter into Command Mode from any other mode, it requires pressing
the [Esc] key. If we press [Esc] when we are already in Command Mode, then vi
will beep or flash the screen.

Insert mode: This mode enables you to insert text into the file. Everything that’s
typed in this mode is interpreted as input and finally, it is put in the file. The vi
always starts in command mode. To enter text, you must be in insert mode. To

36

Downloaded by GULSHAN KUMAR 1149


come in insert mode you simply type i. To get out of insert mode, press the Esc
key, which will put you back into command mode.

Last Line Mode(Escape Mode): Line Mode is invoked by typing a colon [:],
while vi is in Command Mode. The cursor will jump to the last line of the screen
and vi will wait for a command. This mode enables you to perform tasks such as
saving files, executing commands.
Editing and inserting in Files(Entering and Replacing Text): To edit the file, we
need to be in the insert mode. There are many ways to enter insert mode from the
command mode.
I : Inserts text before current cursor location.
I : Inserts text at beginning of current line.
A : Inserts text after current cursor location.
A : Inserts text at end of current line.
O : Creates a new line for text entry below cursor location.
O : Creates a new line for text entry above cursor location.
R : Replace single character under the cursor with the next character typed.
R : Replaces text from the cursor to right.
S : Replaces single character under the cursor with any number of characters.
S :Replaces entire line.
Moving within a File(Navigation):
To move around within a file without affecting text must be in command mode
(press Esc twice). Here are some of the commands can be used to move around one
character at a time.
Commands and their Description
K : Moves the cursor up one line.
J : Moves the cursor down one line.
H : Moves the cursor to the left one character position.
L : Moves the cursor to the right one character position.
0 or | : Positions cursor at beginning of line.
$ : Positions cursor at end of line.
W : Positions cursor to the next word.
B : Positions cursor to previous word.
( : Positions cursor to beginning of current sentence.
) : Positions cursor to beginning of next sentence.
H : Move to top of screen.
nH : Moves to nth line from the top of the screen.
M : Move to middle of screen.

L : Move to bottom of screen.

37

Downloaded by GULSHAN KUMAR 1149


nL : Moves to nth line from the bottom of the screen.
Colon along with x : Colon followed by a number would position the cursor on line
number represented by x.
Control Commands(Scrolling): There are following useful commands which can
used along with Control Key:
Commands and their Description:
CTRL+d : Move forward ½ screen.
CTRL+f : Move forward one full screen.
CTRL+u : Move backward ½ screen.
CTRL+b : Move backward one full screen.
CTRL+e : Moves screen up one line.
CTRL+y : Moves screen down one line.
CTRL+u : Moves screen up ½ page.
CTRL+d : Moves screen down ½ page.
CTRL+b : Moves screen up one page.
CTRL+f : Moves screen down one page.
CTRL+I : Redraws screen.
SHELL PROGRAMMING
A shell program runs in interpretive mode. It is not compiled to a separate
executable file as a C program is. Each statement is loaded into memory when it is
to be executed. Shell scripts consequently run slower than those written in high-
level languages. Speed is not a factor in many jobs we do, and in many cases, using
the shell in an advantages- especially in system administrative tasks. The Unix
system administrator must be accomplished shell programmer.

SHELL SCRIPTS
When a group of command have to be executed regularly, they should be stored in
a file, and the file itself executed as a shell script or shell program. Though it’s not
mandatory, we normally use the .sh extension for shell scripts. Shell scripts are
executed in a separate child shell process, and this sub-shell need not be the same
as your login shell. By default, the child and parent shells belongs to the same type,
but you can provide a special interpreter line in the first line of the script to specify
a different shell for your script. Use your vi editor to create the shell script,
script.sh.
EDITOR COMMANDS

Editors :
In an operating system, a editor is assumed authority which helps to create
and modify users files in data. Any ASCII text files such as a program or a

38

Downloaded by GULSHAN KUMAR 1149


document may be created or modified using a text editor. There are three text
editors present under UNIX i.e.
 Ed - line editor

 Vi - Screen editor

 Sed - Stream editor

C Ed :

It is just a line editor, like edlin in DOS. It is an older standard


Unix editor originally written by Ken Thompson and available on
every Unix system. It takes no advantage on special terminal features.
So it can work on any terminal. It also forms the basis of other
essential programs. Ed was designed in early 1970's for a computing
environment and was derived from an earlier editor called Qed. Syntax
: ed <filename>
C VI EDITOR :

UNIX provides a very versatile one—vi. Bill Joy created


this editor for the BSD system. The program is now standard on all the
UNIX system. Vi uses a number of internal commands to navigate to any
point in a text file and edit the text there. It also allows you to copy and
move text within a file and also from one file to another. Vi offers cryptic,
and sometimes mnemonic, internal commands for editing work. MODES
USED BY VI :
C COMMAND MODE :

The default mode of the editor where every key is


interpreted as a command to run on text. You will have to be in this
mode to copy and delete text. Unnecessary pressing of Esc in this
mode sounds a beep but also confirms that you are in this mode.
C INPUT MODE :

Every key pressed after switching to this mode actually


shows up as text.Pressing Esc in this mode takes vi to command
mode.

COMMAND FUNCTION
I Inserts text to left of cursors.
A Appends text to right of cursor.
I Inserts text at beginning of line.

39

Downloaded by GULSHAN KUMAR 1149


A Appends text at end of line.
O Opens line below.
O Opens line above.
Replaces single character under cursor with ch
Rch
(No [Esc] required).
Replaces single character under cursor with any
R
number of characters.
Replaces single character under cursor with any
S
number of characters.
S Replaces entire line.

C EX MODE OR last line mode :

The mode used to handle files and perform


substitution. Pressing a: in the command mode invokes this mode. You
then enter an ex mode command follows by [Enter]. After the command
is run, you are back to the default command mode.

COMMAND ACTION
:w Saves file and remains in editing mode.
:x Saves file and quits editing mode.
:wq As above.
:w n2w.p1 Like Save As …. In Microsoft windows.
:w! n2w.p1 As above, but overwrites existing file.
:q Quits editing mode when no changes are made to file.
:q! Quits editing mode but after abandoning changes.
:n1,n2w
Write lines n1 to n2 to file build.sql.
build.sql
:.w build.sql Write current line to file build.sql.
:$w build.sql Write last line to file build.sql.
:sh Escapes to UNIX shell.
:recover Recovers file from a crash.

NAVIGATION:
In this we consider the command mode. This is the mode
you come to when you have finished entering or changing your text. A
Command Mode command doesn’t show up on screen but simply performs a
function. We begin with navigation. Don’t forget to avoid the cursors control
keys for navigation.
40

Downloaded by GULSHAN KUMAR 1149


KEY FUNCTION
K Moves cursor up.
J Moves cursor down.
H Moves cursor left.
SL Moves cursor right.
B Moves back to the beginning of word.
E Moves forward to the beginning of word.
W Moves forward to the end of word.
O Moves the cursor to the positioned column.
$ Moves to the end of line.
G Goes to end of file.

EDITING TEXT :
The editing facilities in vi are very elaborate and involve the use of
operators.
Keys for Editing Text :

KEY FUNCTION
D Delete
Y Yank (Copy)
X Deletes a single character
dd Removes the entire line.
P/p Put the text at the new location with p or P.
yy Yanks (copy) current line
Removes the new-line character between two lines to
J
pull up line below it

Result: Basic introduction about Shell Programming and Shell script is given
Outcome: Students will learn about the basic introduction of Shell Programming

41

Downloaded by GULSHAN KUMAR 1149


SHELL PROGRAMS

Objectives:To create a script to enter a string and then print its manipulation
table.

$ cat table.sh

# To print multiplication table

echo "Enter a number for which the multiplication table is to be written "

read number1

echo "The length up to which table is to be written "

read number2

echo "Multiplication table for" $number1 " is given below "

count=1

while [ $count -le $number2 ]

do

result=`expr $number1 \* $count`

echo $count "*" $number1 "=" $result

count=`expr $count + 1`

done

OUTPUT :

42

Downloaded by GULSHAN KUMAR 1149


$ shtable.sh

Enter a number for which the multiplication table is to be written

The length upto which table is to be written

10

Multiplication table for 2 is given below

1*2=2

2*2=4

3*2=6

4*2=8

5 * 2 = 10

6 * 2 = 12

7 * 2 = 14

8 * 2 = 16

9 * 2 = 18

10 * 2 = 20

Result:Script is created to enter a string and its manipulation table is printed


Outcome: Students will learn the creation of script to enter a string and printing of
its manipulation table

Objectives: To create a script to accept a number and compute it's factorial.

$ cat factorial.sh
43

Downloaded by GULSHAN KUMAR 1149


# To compute the factorial

echo "Enter the number whose factorial is to be computed"

read num

temp=`expr $num - 1`

while [ $temp -ge 1 ]

do

num=`expr $num \* $temp`

temp=`expr $temp - 1`

done

echo "The factorial of number is : $num"

OUTPUT:

$ shfactorial.sh

Enter the number whose factorial is to be computed

The factorial of number is : 120

Result:Script is created to accept a number and compute its factorial.

44

Downloaded by GULSHAN KUMAR 1149


Outcome: Students will learn the creation of script to accept a number and to
compute its factorial.
Objectives: Write a script to determine whether a given number is prime or
not.

$ cat prime.sh

# To find the number is prime or not

echo "Enter no: "

read num

i=2

while [ $i –le $num ]

do

if [ `expr $num % $i ` –eq 0 ]

then

break

fi

i=`expr $i + 1`

done

if [ $i -eq $num ]

then

echo "$num is a prime number"

45

Downloaded by GULSHAN KUMAR 1149


else

echo "$num is not a prime number"

fi

OUTPUT :

$ shprime.sh

Enter no:

4 is not a prime no.

$ shprime.sh

Enter no:

7 is a prime number

Result:Script is created to determine whether a given number is prime or not.

Outcome: Students will learn the creation of script to determine whether a given
number is prime or not.

46

Downloaded by GULSHAN KUMAR 1149


Objectives:Write a shell script to find out whether the number entered is odd
or even.

$ cat odd.sh

# check whether the entered number is even or odd

echo "Enter a no.: "

read n

x=`expr $n % 2`

if [ $x -eq 0 ]

then

echo "EVEN"

else

echo "ODD"

fi

OUTPUT :

$ shodd.sh

Enter a no.:

EVEN

47

Downloaded by GULSHAN KUMAR 1149


$ shodd.sh

Enter a no.:

15

ODD

Result:Script is created to find out whether the number entered is odd or even

Outcome: Students will learn the creation of script to find out whether the number
entered is odd or even.

Objectives: To Create a shell script ‘addphone’ that asks a user for a name and
then a

# phone Number. The name and phone number will be put in a file
# ‘phonebook’. You should be able to run ‘addphone’ several times without
# destroying the previous contents of ‘phonebook’.

# cat addphone.sh

# To enter a list of names

c=1

while [ $c –eq 1 ]

do

echo "Please enter the name of person"

read name

echo "Please enter the phone number of person"

48

Downloaded by GULSHAN KUMAR 1149


read phone

echo $name >> phonebook

echo $phone >> phonebook

echo "Press 1 to continue , 2 to exit"

read c

done

OUTPUT:

$ shaddphone.sh

Please enter the name of person Deepak

Please enter the phone number of person 3957417897

Press 1 to continue, 2 to exit 1


Please enter the name of person Rahul

Please enter the phone number of person

9888165135 Press 1 to continue, 2 to exit 1

Please enter the name of person Rohit

Please enter the phone number of person

9872821444 Press 1 to continue, 2 to exit 2

$cat phonebook

Deepak

3957417897

Rahul

49

Downloaded by GULSHAN KUMAR 1149


9888165135

Rohit

9872821444

Result: Script is created ‘add phone’ that asks a user for a name and then a phone
Number

Outcome: Students will learn the creation of ‘add phone’ that asks a user for a name
and then a phone Number

50

Downloaded by GULSHAN KUMAR 1149


EXPERIMENT-6

AIM: Implementation of Bankers algorithm for the purpose of deadlock


avoidance.

THEORY: 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 need ‘k’ instances of resource type Rj
For its execution.
Need [ I, j ] = Max [ I, j ] – Allocation [ I, j ]

51

Downloaded by GULSHAN KUMAR 1149


Allocationi specifies the resources currently allocated to process Pi and Needi
specifies the additional resources that process Pi may still request to complete its
task.

Algorithm:
Banker’s algorithm consists of Safety algorithm and Resource request algorithm

Safety Algorithm
The algorithm for finding out whether or not a system is in a safe state can be
described as follows:
1) 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[i]
Finish[i] = true
Goto step (2)
4) Finish [i] = true for all i
Then the system is in a safe state

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

52

Downloaded by GULSHAN KUMAR 1149


Needi = Needi– Requesti

Program:
#include <stdio.h>
Int main()
{
// P0, P1, P2, P3, P4 are the Process names here
Int n, m, I, j, k;
N = 5; // Number of processes
M = 3; // Number of resources
Int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
Int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
Int avail[3] = { 3, 3, 2 }; // Available Resources
Int f[n], ans[n], ind = 0;
For (k = 0; k < n; k++) {
F[k] = 0;
}
Int need[n][m];
For (I = 0; I < n; i++) {
For (j = 0; j < m; j++)
Need[i][j] = max[i][j] – alloc[i][j];
}
Int y = 0;
For (k = 0; k < 5; k++)
{ For (I = 0; I < n; i++)
{
If (f[i] == 0) {
Int flag = 0;
For (j = 0; j < m; j++) {
If (need[i][j] > avail[j])
{ Flag = 1;
Break;

53

Downloaded by GULSHAN KUMAR 1149


}
}
If (flag == 0)
{ Ans[ind++] = I;
For (y = 0; y < m; y++)
Avail[y] += alloc[i][y];
F[i] = 1;
}
}
}
}
Printf(“Following is the SAFE Sequence\n”);
For (I = 0; I n – 1; i++)
Printf(“ P%d ->”, ans[i]);
Printf(“ P%d”, ans[n – 1]);
Return (0);
}
Output:
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2
Result: Thus the Bankers algorithm was executed and verified successfully
Outcome: Students will learn about the execution of Bankers Algorithm.

54

Downloaded by GULSHAN KUMAR 1149

You might also like