OSY Solved Manual @diploma - World

Download as pdf or txt
Download as pdf or txt
You are on page 1of 160

LIST OF PRACTICALS

Sr. Title of the practical Page Date Date of Assessme Dated Remar
No No. of submiss nt Marks sign. of k s (if
perfo ion (50) teacher any)
r
manc
e
1. Install and configure
Linux (or alike) operating
system.
2. Execute general purpose
commands date, time, cal,
clear, banner, tty, script,
man.
3. Work with multiple linux
terminals and basic
commands : who, who am
I, login, passwd, su, pwd.
4. a) Use Operating services
(Editor, GUI, File
handling)
b) Run commands to start,
stop, and restart the
specified services in
Linux.
5. Execute process
commands – ps, wait,
sleep, exit, kill.
6. Execute file and directory
manipulation commands –
ls, rm, mv, cp, join, split,
cat (file saving and
reduction operator), head,
tail, touch.

7. Execute file and


directory manipulation
commands – diff,
comm, pr, chmod,
mkdir, rmdir, cd, pwd
,dir , cmp. (Use wild
card character).
8. Execute text processing tr,
wc, cut, paste, spell, sort,
grep, more.
9. Use vi editor and perform
all the editor commands.
10. Write and execute Shell
Script by using following
Control Statements
features – ―if‖ statement.

11. Write and execute Shell


Script by using following
Control statements
features – ―for‖ statement,
exit, break, continue.

12. Write Shell Scripts to


find out whether – Given
file exists ?

13. Write Shell Script to find


out whether – File has
read, write, and execute
permissions?
14. Write a program to
calculate total waiting and
turnaround time of n
processes with First Come
First Serve CPU
scheduling algorithm.

15. Write a ‗C‘ program to


implement FIFO page
replacement Algorithm.
Practical 1 : Install and configure Linux (or alike) operating system.

PRACTICAL SIGNIFICANCE :
Linux is the base of many of open source operating system designed to replace Windows and
Mac OS .It is free to download and install on any computer because it is open source. There are a
variety of different versions or distributions or available developed by different by different
groups. To prevent hacking attempts, Many organizations keep their LINUX operating system
private, many others make their variations of Linux available publicly So the whole can benefit
and large.

MINIMUM THEORETICAL BACKGROUND :


STEPS :

1) Download the ISO file.


2) Boot your system with Bootable DVD/USB drive. To start the installation click on
―Install Ubuntu‖ .
3) Check Install prerequisite.
4) Select the Installation Type.
5) Select your respective Time Zone.
6) Select your respective Keyboard Layout.
7) Set the Hostname of your system and User credentials that will be used after installation.
Installation has started. Once the installation is completed, it will ask to restart the
Machine. Click on ―Restart Now‖.
8) Login Screen after reboot. Use the same user and its credentials that we have set during
the installation. We will get below screen after entering the credentials. Ubuntu
Installation is Completed Now.

Similarly any open source installation shall be considered.

PROGRAM CODE :
1) Install and configure Linux (or similar) operating system on your computer. Write down
the steps for the same.

Ans.
Steps :

1) Download the Linux distribution of your choice.


2) Boot into the Live CD or Live USB.
3) Try out the Linux distribution before installing.
4) Start the installation process.
5) Create a username and password.
6) Set up the partition.
7) Boot into Linux.
8) Check your Hardware.
9) Start using Linux.

RESULT :
We successfully installed Linux Operating System (Ubuntu).

PRACTICAL RELATED QUESTIONS :


1) What are different versions of Linux Operating System?

Ans.

 Debian
 Gentoo
 Ubuntu
 Linux Mint
 Red Hat Enterprise Linux
 CentOS
 Fedora
 Kali Linux

2) Enlist the steps for booting the operating system.

Ans. Booting Process Steps :

 BIOS and setup program


 The POST (Power-On-Self-Test)
 The OS (Operating System) Loads
 System Configuration
 System Utility Loads
 Users Authentication

3) State names of latest multi-user operating system and its advantages.

Ans. Latest multi-user operating system :

 Windows NT
 Windows 2000
 Windows XP
 Windows Vista
 Mac OS X
 Linux
 FreeBSD
 NetBSD

Advantages :

1) You would be able to run different programs on their native OS.


2) You would have a great deal of versatility in what you can do with your computer.
(eg. Gaming and software development, Windows and Linux software development
on the same system, etc)
3) You can also do things in one OS that you wouldn‘t be able to do in your main OS.
(Linux/FreeBSD could give you more control than Win10)
4) If you use your computer for work, then you can also use it for separate work and
leisure.

EXERCISE :
1) Differentiate between Command Line OS and GUI OS by giving example.

Ans.

CLI GUI
CLI is difficult to use. GUI is easy to use.
It consumes more memory. It consumes less memory.
High precision is obtained. Low precision is obtained.
Faster than GUI. Slower than CLI.
Needs only keyboard. Needs keyboard as well as mouse.
Input is entered only on command prompt. Input can be entered anywhere on the
screen.
No menus provided. Menus are provided.
No use of graphics. Uses Graphics.
Does not use any pointing devices. It uses pointing devices for selecting or
choosing options.
Examples: Microsoft Windows, DOS Examples: Microsoft Windows, macOS,
Shell, Mouse Systems PowerPanel Ubuntu Unity, Android, Apple's iOS,
BlackBerry OS, Windows 10 Mobile, Palm
OS-WebOS, and
Firefox OS for smartphones.

2) Draw the diagram of multiprogramming system and state concept of it.

Ans. Sharing the processor, when two or more programs reside in memory at the same time,
is referred as multiprogramming. Multiprogramming assumes a single shared processor.
Multiprogramming increases CPU utilization by organizing jobs so that the CPU always has
one to execute.
3) Which are the extra facilities provided by Unix other than windows OS?

Ans.

 Unix is more flexible and can be installed on many different types of machines,
including main-frame computers, supercomputers and micro-computers.
 Unix is more stable and does not go down as often as Windows does, therefore
requires less administration and maintenance.
 Unix has greater built-in security and permissions features than Windows.
 Unix possesses much greater processing power than Windows.

4) In list four features of the following operating system.

Ans.

a) Windows 98
1. Integrated Microsoft Internet Explorer in Windows Explorer and Help System.
2. Quick Launch tool bar.
3. Windows 98 came up with a tool called System File Checker that scans and
restore corrupt or missing system files.
4. Extended support for the connection to networks.
b) Windows 2000
1. Support for FAT16, FAT32, and NTFS.
2. Increased uptime of the system and significantly fewer OS reboot scenarios.
3. Windows Installer tracks applications and recognizes and replaces missing
components.
4. Protects memory of individual apps and processes to avoid a single app bringing
the system down.
c) Windows XP
1. Reliability [Home and Professional] Configured on the reliability-proven kernel
of Windows 2000.
2. Faster response even in processing multi-tasks [Home and Professional].
3. Retention of data security and protection of user privacy.
4. Multi-task [Home and Professional] Operate multiple applications at the same
time.

CONCLUSION : We have successfully completed installation of Linux operating system.


In this practical we have studied the versions, booting process, etc. of operating system.

Practical 2 : Execute general purpose commands date, time, cal,


clear, banner , tty, script, man

PRACTICAL SIGNIFICANCE :
General purpose commands are inbuilt programs that can be invoked in multiple ways. These
commands work interactively from a terminal. A terminal that provides a command line interface
using shell program.

MINIMUM THEORETICAL BACKGROUND :


Specifying the date format
(+ is used to concatenate date command with descriptor)

PROGRAM CODE :
1) Execute general purpose commands date, time, cal, clear, banner , tty, script, man.

Ans.

1) date

2) time

3) cal
4) clear

5) banner

6) tty

7) script
8) man

2) Write down different options for cal commands. (use $man cal)

Ans.

-h : Turns of highlighting of today.

-J : Display Julian Calendar, if combined with the –o option, display date of Orthodox
Easter according to the Julian Calendar.

-e : Display date of Easter (for western churches).

-j : Display Julian days (days one-based, numbered from January 1).

-m month : Display the specified month. If month is specified as a decimal number,


appending ‗f‘ or ‗p‘ displays the same month of the following or previous year respectively.

-o : Display date of Orthodox Easter (Greek and Russian Orthodox Churches).


-p : Print the country codes and switching days from Julian to Gregorian Calendar as they
are assumed by ncal. The country code as determined from the local environment is marked
with an asterisk.

-s country_code : Assume the switch from Julian to Gregorian Calendar at the date
associated with the country_code. If not specified, ncal tries to guess the switch date from
the local environment or falls back to September 2, 1752. This was when Great Britain and
her colonies switched to the Gregorian Calendar.

-w : Print the number of the week below each week column.

-y : Display a calendar for the specified year. This option is implied when a year but no
month are specified on the command line.

-3 : Display the previous, current and next month surrounding today.

-1 : Display only the current month. This is the default.

-A number : Months to add after. The specified number of months is added to the end of the
display. This is in addition to any date range selected by the -y, -3, or -1 options. For
example, ―cal -y -B2 -A2‖ shows everything from November of the previous year to
February of the following year. Negative numbers are allowed, in which case the specified
number of months is sub‐tracted. For example, ―cal -y -B-6‖ shows July to December. And
―cal -A11‖ simply shows the next 12 months.

-B : Months to add before. The specified number of months is added to the beginning of the
display. See -A for examples.

-C : Completely switch to cal mode. For cal like output only, use -b instead.

-N : Switch to ncal mode.

-d yyyy-mm : Use yyyy-mm as the current date (for debugging of date selection).

-H yyyy-mm-dd : Use yyyy-mm-dd as the current date (for debugging of highlighting).

-M : Weeks start on Monday.

-S : Weeks start on Sunday.

-b : Use oldstyle format for ncal output.

3) Write options of date command.(Use $man date).


Ans.

-d, --date=STRING : display time described by STRING, not 'now'

--debug : annotate the parsed date, and warn about questionable usage to stderr

-f, --file=DATEFILE : like --date; once for each line of DATEFILE

-I[FMT], --iso-8601[=FMT] : output date/time in ISO 8601 format. FMT='date' for


date only (the default), 'hours', 'minutes', 'seconds', or 'ns' for date and time to the indicated
precision. Example: 2006-08-14T02:34:56-06:00

-R, --rfc-email : output date and time in RFC 5322 format. Example: Mon, 14 Aug 2006
02:34:56 -0600

--rfc-3339=FMT : output date/time in RFC 3339 format. FMT='date', 'seconds', or 'ns' for
date and time to the indicated precision. Example: 2006-08-14 02:34:5606:00

-r, --reference=FILE : display the last modification time of FILE

-s, --set=STRING : set time described by STRING

-u, --utc, --universal : print or set Coordinated Universal Time (UTC)

--help : display this help and exit

--version : output version information and exit

PRACTICAL RELATED QUESTIONS :

1) How you record all the activities performed by the user.

Ans. Script command is used to record all the terminal activities. By default all the
information is saved in file typescript. And to stop the typescript exit command is used.
Syntax: script [options] [file]

2) Give a command to display calendar for month of January.

Ans.
 While the cal/ncal commands display the current month by default, you can use the -
m command-line option in order to have a specific month displayed.
 This option requires a numeric value (1-12) that represents the month you want the
command to display.
 To display the month of January of current year: cal -m1
 To display calendar of specific month and year: cal [ [month] year].

3) Give a single command to display the calendar of pervious, current and next month.

Ans. cal -3 command is used to display the calendar of pervious, current and next month.

4) Give the command to display full week day (eg. Sunday) using date command.

Ans. %A is used as Locale‘s abbreviated full weekday name (e.g., Sunday)

EXERCISE :
1) What is the output of the following commands?

Ans

a) $cal 04 2019

b) $date ―+Today‘s information: %D and %B‖;cal


c) $date ―+My clock is showing %H hours, %M minutes and %S seconds‖

d) $cal -3

e) $cal -5

f) $cal -2000

2) Give the syntax of commands for displaying the output. (use date)

Ans.

a) This is ………. Month of the year ………. (Abbreviation for the month and 4-digit
year)

Ans. date ―+This is %b month of the year %Y‖


b) This is the ………. th day of this year.

Ans. date ―+This is %j th day of this year‖

CONCLUSION : We successfully implemented commands to perform operations using


commands like date, time, cal, clear, banner , tty, script, man.

Practical 3 : Work with multiple Linux terminals and basic


commands

PRACTICAL SIGNIFICANCE :
Work with terminal environment to know about users and set their security. It includes current
status of all the users like details about all the users who accesses the terminal for particular
duration and path of directory.
MINIMUM THEORETICAL BACKGROUND :

PROGRAM CODE :
List down with all options for who commands and write its description. Note: Write terminal's
output in Result Section.
RESULT :
PRACTICAL RELATED QUESTIONS :
1) Give command for present working directory.

Ans. pwd

2) State currently login users by command.

Ans. who

3) Acquire the status of super user.

Ans.
EXERCISE :
1) Acquire the status of super user.

Ans.

2) Write output for following commands


i) $who;clear;whoami
ii) $who;tty;date

Ans.

i)
ii)

CONCLUSION : We successfully implemented basic commands with multiple linux


terminals.
Practical 4: Working With a) operating system services b)
Processes

PRACTICAL SIGNIFICANCE :
The purpose of computer systems is to allow the user to excute programs. So the Operating
system provides an environment where the user can conveniently run programs. The user does
not have to worry about the memory allocation or multitasking or anything. These things are
taken care of by the operating systems.

MINIMUM THEORETICAL BACKGROUND :


An Operating System supplies different kinds of services to both the users and to the
programs as well.it also provides application programs (that run within an Operating system) an
environment to execute it freely. It provides users the services run various programs in a
convenient manner. File editing is done with the help of any editor. The default editor that comes
with the UNIX operating system is called vi(visual editor). The UNIX vi editor is a full screen
editor and has two modes of operation: Command mode commands which cause action to be
taken on the file, and Insert mode in which entered text is inserted into the file.

Editor : There are many ways to edit files in Unix. Vi Editor works in Unix. This editor enables
you to edit lines in context with other lines in the file. You can also use this editor to just read a
text file. An improved version of the vi editor which is called the VIM has also been made
available now. Here, VIM stands for Vi Improved.

GUI : Linux system provides both the interface that is GUI and CLI.As per the requirement
you can decide when you should use the Linux command line interface (CLI) and when you
should use a graphical user interface (GUI).
PROGRAM CODE :
Check all permissions started on your system. Stop the services which are not required for
long time.

We execute following commands on ubuntu operating system:

1) Sudo systemctl start acpit


2) Sudo systemctl stop ufw
3) Sudo systemctl start ufw
4) Sudo systemctl restart ufw
5) Pwd
6) Cd

RESULT :

 cd

 pwd
 Sudo systemctl stop ufw

 Sudo systemctl start ufw


 Sudo systemctl restart ufw
PRACTICAL RELATED QUESTIONS :
1) List various menus you observed on your system.

Ans. Menu may be defined as the commands and operations in a list which is presented to the
user in a computer system or communication system in terms of computing and
telecommunication.

The various menus observed in the system are :

 Pop up menu
 Menu bar
 Command Line Interface menu
 Graphical User Interface menu

There are more menus but these are the most required and observed menu on the system.

2) Study the GUI of your Linux system

Ans. Default installation of Ubuntu contains a wide range of software that includes
LibreOffice, Firefox, Thunderbird, Transmission, and several lightweight games such as
Sudoku and chess. Many additional software packages are accessible from the built in
Ubuntu Software (previously Ubuntu Software Center) as well as any other APTbased
package management tools. Many additional software packages that are no longer installed
by default, such as Evolution, GIMP, Pidgin, and Synaptic, are still accessible in the
repositories and installable by the main tool or by any other APT-based package management
tool. Cross-distribution snap packages and flatpaks are also available, that both allow
installing software, such as some of Microsoft's software, in most of the major Linux
operating systems (such as any currently supported Ubuntu version and in Fedora). The
default file manager is GNOME Files, formerly called Nautilus. All of the application
software installed by default is free software. In addition, Ubuntu redistributes some
hardware drivers that are available only in binary format, but such packages are clearly
marked in the restricted component.

3) What is difference between GUI and CLI?

Ans.
EXERCISE :
1) What are system calls provided by file management?

Ans. File Management

These system calls are responsible for file manipulation such as creating a file, reading a file,
writing into a file etc.

For Windows following are the File management system calls

 createFile()
 readFile()
 writeFile()
 closeHandle()

For Linux following are the File management system calls

 open()
 read()
 write()
 close()
2) Draw and explain services provided by operating system

Ans.

Following are a few common services provided by an operating system –

1) Program execution
2) I/O operations
3) File System manipulation
4) Communication
5) Error Detection
6) Resource Allocation
7) Protection

1. Program execution : Operating systems handle many kinds of activities from user
programs to system programs like printer spooler, name servers, file server, etc. Each of
these activities is encapsulated as a process. A process includes the complete execution
context (code to execute, data to manipulate, registers, OS resources in use).
2. I/O Operation : An I/O subsystem comprises of I/O devices and their corresponding
driver software. Drivers hide the peculiarities of specific hardware devices from the user.
3. File system manipulation : A file represents a collection of related information.
Computers can store files on the disk (secondary storage), for long-term storage purpose.
Examples of storage media include magnetic tape, magnetic disk and optical disk drives
like CD, DVD. Each of these media has its own properties like speed, capacity, data
transfer rate and data access methods.
4. Error handling : Errors can occur anytime and anywhere. An error may occur in CPU, in
I/O devices or in the memory hardware.
5. Resource Management : In case of multi-user or multi-tasking environment, resources
such as main memory, CPU cycles and files storage are to be allocated to each user or
job.
6. Protection : Considering a computer system having multiple users and concurrent
execution of multiple processes, the various processes must be protected from each
other's activities.

3) What are system components of operating system?

Ans.

 File Management.
 Process Management.
 I/O Device Management.
 Network Management.
 Main Memory management.
 Secondary-Storage Management.
 Security Management.

CONCLUSION : We have successfully execute all the commands of Linux operating


system of GUI, editor and file handling commands. Commands are as follows :

 Sudo systemctl start acpit


 Sudo systemctl stop ufw
 Sudo systemctl start ufw
 Sudo systemctl restart ufw
 Pwd
 Cd
Practical 5 : Execute process commands - ps, wait, sleep, exit, kill

PRACTICAL SIGNIFICANCE :
Process is program in execution.ps commands is used to manage and to see the active processes
on Unix operating system. Ps basically means ‗Process Status‘ which is used to display currently
running processes in Unix operating system.

MINIMUM THEORETICAL BACKGROUND :


1) ps
 Program running on the system are called as processes. For examining these
processes, users need to know about ps command.
 This command is useful in producing the information for all the processes that are
running on the machine.
 The ps command is not easy to use as it presents number of parameters that makes
it complicated.
2) wait
 The wait is one of the built-in commands of Linux. It waits for the completion of
any running process.
 Waits until all background processes are completed and then exits.
3) sleep
 Sleep command is used to introduce delay for a specific time.This command helps
to pause a process for a given time.
 Suffixes can be used with command to specify exact time. ―s‖ can be used for
seconds. ―m‖ can be used for minutes, ―h‖ can be used for hours and ―d‖ can be
used for days.
4) exit
 Generally shell script will exit with the last command‘s exit status.
 Used to quite the shell.
5) kill
 Kill command is used to kill the process. User has to specify process ID for
killing the process.
 Kill command sends TERMINATE signal to all the process IDs that are listed on
command line.
 It may be difficult to use kill command as it uses process ID instead of its
command name.
 For killing the process user should be the owner of process or must have logged in
from root user.

PROGRAM CODE :
 $ ps

 $ sleep 10

 $ kill
 $ wait

 $ exit

PRACTICAL RELATED QUESTIONS :


1) What is name of your login shell?

Ans. ps -p $$ – Display your current shell name reliably.

2) What are various options of kill command?

Ans.

1. $kill –l : To display all the available signals


2. $kill pid : To show how to use a PID with the kill command.
Syntax : $kill pid

3. kill -s : To show how to send signal to processes.


Syntax : kill {-signal | -s signal} pid
4. kill -L :This command is used to list available signals in a table format.
Syntax : kill {-l | --list[=signal] | -L | --table}

3) What are various options of ps command?

Ans.

Option Description

-a Displays all processes on a terminal, with the exception of group .

-c Displays scheduler data.

-d Displays all processes with the exception of session leaders.

-e Displays all processes.

-f Displays a full listing.

-glist Displays data for the list of group leader IDs.

-j Displays the process group ID and session ID.


-l Displays a long listing

-plist Displays data for the list of process IDs.

-slist Displays data for the list of session leader IDs.

-tlist Displays data for the list of terminals.

-ulist Displays data for the list of usernames.

4) Explain about exit command.

Ans. exit command in linux is used to exit the shell where it is currently running. It takes one
more parameter as [N] and exits the shell with a return of status N. If n is not provided, then
it simply returns the status of last command that is executed.

Syntax : exit [n]

5) List the system calls for process management

Ans. System calls Description

fork() : To create a new process

exec() : To execute a new program in a process

wait() : To wait until a created process completes its execution

exit() : To exit from a process execution

getpid() : To get a process identifier of the current process

getppid() : To get parent process identifier

nice() : To bias the existing priority of a process

brk() : To increase/decrease the data segment size of a process

EXERCISE :
1) Observe the output of following commands
$sleep 30; date
$echo $$

Ans.

2) Display full listing of all processes running on your terminal.

Ans.

3) Write output of following command.


$sleep 60; banner GOOD

Ans.

4) Difference between Wait and Sleep

Ans.

Key Wait Sleep


Class Wait() method belongs to Sleep() method belongs to
Object class Thread class
Lock Release Wait() releases the lock on an It does not release lock on an
object object
Calling context Wait() can be called on Sleep() can be called on
object itself Thread.
Wake-up condition Until call notify(), notifyAll() Until atleast time expire or
from object call interrupt.
spurious wakeups Program can get spurious It will not get spurious
wakeups wakeups.

5) Write all the process commands

Ans.

1. ps - If you run ps command without any arguments, it displays processes for the current
shell.
2. Wait -When wait command is executed with $process_id then the next command will
wait for completing the task of the first echo command. The second wait command is
used with '$! ' and this indicate the process id of the last running process.
3. Sleep - command is used to delay for a fixed amount of time during the execution of any
script.
4. Kill -kill command in Linux (located in /bin/kill), is a built-in command which is used to
terminate processes manually.
5. Exit- used to quite the shell.

CONCLUSION : In this practical we successfully install virtual box, Ubuntu on our laptop.
And successfully Run the basic process commands on Ubuntu.
Practical 6 : Execute file and directory manipulation commands

PRACTICAL SIGNIFICANCE :
Basically the operations performed in unix or linux are done on a prompt or terminal which is
not stored anywhere. but most of the commands are return to store the information. One way is
to store the information in file. Various operation that can be performed on a file are create ,
open, read ,write ,move,close and rename.

MINIMUM THEORETICAL BACKGROUND :


File and directory manipulation commands :

• ls Command: It is used to lists files in current directory.

Syntax: $ls

Options Meanings

ls -a list all files including hidden files starts with ‗.‘

ls -d list directories – with ‗*‘


ls –i list files in I node index number

ls -l list with long format – show permissions

Example:

$ls -I abc.txt list contains of abc.txt files

$ls -l list of all files along with permission given to it

$ls ??? list the names of the files with exact three character in it name

$ls d*s list of file names starts with d and ends with s

$ls -l gives full listing of all files and directories

• Rm commands: it is used to remove files

Syntax: $rm filename

Example:

$rm abc.txt removes abc.txt

$rm abc.txt xyz.txt removes abc.txt and xyz.txt files

$rm * removes all files

• Mv commands: it is used to move a file from one location to another

Syntax: Mv [option] source destination

(consider 3 files having name abc.txt xyz.txt and pqr.txt)

to rename the file abc.txt to aaa.txt(not exists)

$ls

Abc.txt xyz.txt pqr.txt

$mv abc.txt aaa.txt

$ls

Xyz.txt pqr.txt aaa.txt


Options:

1. -i(interactive) : the mv command with -I option asks for confirmation $mv -I abc.txt
aab.txt

• Cp command: it I used to copy a file to destination file. If the command contains two file
names, then it is copies the contains of first file to the second file. If the 2nd file doesn‘t exists
then first it creates one and content is copied to it. But if it existed then it is simply overwritten
without any warning.

Syntax : $cp source file destination file

Example:

$ls

xyz.txt

$cp xyz.txt zzz.txt

Check it now

$ls Xyz.txt zzz.txt

• Join command: It is used for joning lines of two files on the basis of common field in each file
called as a key.

Syntax: $join [-t -o]filename1 filename2

-t field separator

-o Specify the column each table that must be included

Example :

$cat stud1

Ajay 1990

Vijay 1992

Sujit 1991

$cat stud2
Ajay 50

Vijay 62

Sujit 70

$join -t‖:‖ stud1 stud2

Ajay 1990:50

Vijay 1992:62

Sujit 1991:70

• Split command: It is used to split the large file into smaller files. Default size is 1000 lines/file.

Syntax : $split -n filename tag name

-n no.of lines in each smaller file.

-tag name by default the split builds the o/p files named xaa , xab , xac …….

It tags name specified , it replaces x with that tag name

Example :

Split -100 student

Check it now

-ls

Xaa xab xac

• Cat command : It is used to create the file and displaying the contents of file/files.

Syntax: $cat > sample(to create a file)

This is a simple file in UNIX

<Cntrl d>

$cat sample
Where Cat is a command and sample is a argument. this Is sample file in UNIX. User can
display contents of more than one file and called as concatenation.

$cat list1.txt and list2.txt (list2 files at a time)

• Head command: it is used to read the first 10 lines of file.(10 lines by default) the no.of lines
to be displayed maybe specified in the head command.

Syntax: $head -n filename (-n means how many lines to be displayed)

Example :

$head -20 student

Displays the 1st 20 lines of file student.

• Tail command: it is used to print last few numbers of lines(10 by default) of a certain file, then
terminates.

Syntax: $tail{[+/-]n[lbc]}filename

Options meaning

+n Displays all line starting from nth line

-n displays n line from end of the file

L indicates line

B indicates blocks

C indicate character

Example :

$tail -20l student

Displays last 20 lines of student file.

$tail +20l student

Displays all lines starting from 20th lines of the student file.
• Touch command: it is the easiest way to create new,empty files

Syntax: $touch filename

Example :

$touch aaa

File saving and redirection operator : Generally UNIX commands are entered at the keyboard
and output resulting from these commands are displayed on the computer screen. The standard
input and standard output are actually taken or saved to files.

Example :

Output of 1st command is taken as input for 2nd command. In this example output of ls
command is saved into a file out.txt

$ls > out.txt

Combine 2 text files to another file :

$cat list1.txt list2.txt > todo.txt

In this example contents of file list1.txt and list2.txt is saved to todo.txt file.

$cat list1.txt >> list2.txt

It appends the contents list1.txt to list2.txt

It adds the contents at the end of file.

Now check it

$ls list2.txt

PROGRAM CODE :
1) Create three files a1,a2,a3.

Ans.
2) Apply different commands like :
1)ls 2)mv 3)cp
4)rm 5)join 6)split
7)cat 8)head 9)tail
10)touch
and check the list of files at the ends.

Ans.

1) ls

2) mv

3) cp

4) rm
5) join

6) split

7) cat

8) head
9) tail

10) touch

PRACTICAL RELATED QUESTIONS :


1) What are different options of ls commands? Write down the command along with the
option and note down the output.(Use $man ls commands to check options)

Ans.

Answer: ls is a Linux shell command that lists directory contents of files and directories.

Syntax: $ ls [options] [file|dir]

Examples:

1) List directory /home/user/Documents/Books with absolute path.


-$ ls /home/user/Documents/Books
2) List root directory:
-$ ls /
3) List parent directory:
-$ ls ..
4) List user's home directory (e.g: /home/user):
-$ ls ~
5) List with long format:
-$ ls –l
6) Show hidden files:
-$ ls –a
7) List with long format and show hidden files:
-$ ls –la
8) Sort by date/time:
-$ ls –t
9) Sort by file size:
-$ ls –S
10) List all subdirectories:
-$ ls *

Run $ man ls OR $ ls –help to get all information about ls command.


What are different options of mv commands?

Ans.

It has two distinct functions:

(i) It rename a file or folder.


(ii) It moves group of files to different directory.

i. To rename the file a.txt to geek.txt(not exist)-


Syntax: mv [Option] source destination

Code:

$ ls

a.txt b.txt c.txt d.txt

$ mv a.txt geek.txt

$ ls

b.txt c.txt d.txt geek.txt

ii. moving geeks.txt to b.txt(exist):

Code:

$ ls

b.txt c.txt d.txt geek.txt

$ cat geek.txt

India

$ cat b.txt

geeksforgeeks

$ mv geek.txt b.txt

$ ls

b.txt c.txt d.txt

$ cat b.txt

India

2) What is use of split command?

Ans. Split command in Linux is used to split large files into smaller files. It splits the files
into 1000 lines per file(by default) and even allows users to change the number of lines as per
requirement.

Syntax: split [options] name_of_file prefix_for_new_files


3) How to use join command?

Ans. join command is used to join the two files based on a key field present in both the files.

Syntax: $join [OPTION] FILE1 FILE2

EXERCISE :
1) Write output of following commands :
i. Display all files names which starts with ‗a‘ and ends with ‗y‘.
ii. Enlist all the files beginning with ‗m‘ and ending with any range of 1 to 5.
iii. Show the contents of files whose file names contains exactly two characters.
iv. Create a file ABCD.txt, create a copy with XXX.txt. Rename the original file with
AACD.txt. Delete the file XXX.txt.
v. Display the inodes of any two files at the same time.

Ans.

i. Display all files names which starts with ‗a‘ and ends with ‗y‘.

ii. Enlist all the files beginning with ‗m‘ and ending with any range of 1 to 5.

iii. Show the contents of files whose file names contains exactly two characters.
iv. Create a file ABCD.txt, create a copy with XXX.txt. Rename the original file with
AACD.txt. Delete the file XXX.txt.

v. Display the inodes of any two files at the same time.

2) List all file processing commands

Ans.

a) awk
b) grep
c) head
d) tail
e) sort
f) uniq
g) less
h) more
i) tr
j) pr
k) fmt
l) Sed

3) How many lines will be displayed with head command if number is not specified.
Ans. 10 lines

4) Create two files chapter1 and chapter2 by asking the user before overwrite.
i. Copy contents of chapter1 and chapter2 by asking the user before overwrite.
ii. Display inodes of two files.
iii. Rename the file ‗chapter1‘ to ‗Lessson1‘

Ans.

i. Copy contents of chapter1 and chapter2 by asking the user before overwrite.

ii. Display inodes of two files.

iii. Rename the file ‗chapter1‘ to ‗Lessson1‘

5) Execute the following commands:


i. $ls a*n
ii. $ls s?
iii. cat abc>>xyz

Ans.

i. $ls a*n

ii. $ls s?
iii. cat abc>>xyz

CONCLUSION : We successfully implemented file and directory manipulation commands


like ls, mv, cp, rm, join, split, cp, head, tail, touch.
Practical 7 : Execute File and Directory Manipulation commands

PRACTICAL SIGNIFICANCE :
Data and programs are stored in Files. These are organized in directories. In a simple way, a
directory is just a file that contains other files(or directories).

MINIMUM THEORITICAL BACKGROUND :


Unix uses a hierarchical structure for organizing files and Directories. This structure is called as
a directory tree. The tree has a single root node, the slash character (/), and all other directories
are contained below it. When user first log in to the Unix server, the specified directory is called
as Home Directory.

Directory structure in Unix/Linux:

Directory Manipulation commands are as follows :

a. mdkir
b. cd
c. rmdir
d. pwd
1) mkdir Command
It is used to create a new directory in a current directory .
$ mkdir <directory Name>
Example : $ mkdir CM5I
User can create more than one directory in a single command .
$mkdir subject1 subject2
If user wants to create directory on the specific path them syntax is:
Syntax:
$mkdir path/ directory name

2) cd Command
The Cd command is used to change directory. You can use it to change to any directory
by specifying a valid absolute or relative path.
Syntax:
$cd <directory Name>
Example:
$cd Directory Name
$cd CM5I
$cd To come out from current working directory.
Example :
$cd..
$cd/ It changes to root directory.
Example:
$cd/

3) rmdir Command
It is used to Delete/ remove directory. If the parent directory having subdirectories then
first all subdirectories will be deleted then the parent directory is deleted.
Syntax: $rmdir

4) pwd Command
Pwd stands for present working directory. This is most used linux command to see the
specific Unix directory on which the user is working on.
Syntax: $pwd
diff command
This command is used to show difference between two text files . It also tells which line
in one has to be changed to make the two files identical .
Syntax:
$diff filename1 filename2
The operations of the result should be like this –
a - Added the text to file
c - changes are made in the file
d - deletion operation is performed
< - lines from the first file
> - lines from the second file
$cat file1.txt
I need to go to the shop
I need to buy some mangoes
When I get home , I‘ll wash the cat
$cat file12.txt
I need to go to the shop
I need to buy some mangoes
Oh yeah , I also need to by cheese
When I get home, I‘ll wash the cat
Use the diff command to compare both files.
$diff file1.txt file2.txt
The above command should give the result as shown below-
2a3
>oh yeah, I also need to by cheese
From the output 2a3 means ―After line 2 in the first file, a line to be added: line 3 from
the second file ―.

Comm command
This command compare two sorted files. It compares each line of first file with its
corresponding line in the second file and generates 3 column output.
The first column lists the lines only in first file.
The second column lists the lines only in second file.
The third column lists the lines in both files.
Syntax:
$comm filename1filename2
Example:
$Cat student1 $cat student2
Harsh Harsh
Sujay Niket
Smith Ashutosh
$comm student1 student2
Sujay Niket Harsh
Smith Ashutosh

Pr command

Pr- convert text files for printing


The pr command does minor formatting of files on the terminal screen or for a printer.
For example , if you have a long list of names in a file, you can format it onscreen into
two or more columns.
Syntax:-
Pr option(s) filename(s)
Pr changes the format of the file only one the screen or on printed copy ; it doesn‘t
modify the original file.

dir command
It is used to list all files and directories

chmod command
It is used to change or set permissions ( read, write and execute ) for all the three
categories of users .
Types of users are – user , group and other
To verify The permissions of a file or directory use ls-I command.
Syntax:
$Is -l
Chmod can be operated in two ways:
1. Symbolic or alphabetical Notation.
2. Octal or absolute Notation.

1) Symbolic or Alphabetical Notation


It uses symbols for assigning permissions to the users. There are following symbols
for users of three categories
Syntax:
$Chmod<category ><operation > < permissions> < filename>
Example:
1) Assign the execute permission for user/owner,group and others.
$chmod ugo+x abc
2) Assign all permissions for group
$chmod g+rwx abc
3) Assign execute permission for the owner and remove read permission of group
and others.
$chmod u+x, go-r abc
4) Assign read the permission to all three users and remove all remaining
permissions.
$chmod ugo=r abc

2) Octal and absolute Notation


This method uses a number to specify each set of permissions for the file . It assign
permission in three digits . First digit assign permission for owner, second digit for
group and third for others . Digits range is 0 to 7.
Syntax:
$chmod<three digit octal number><filename>
$chmod [u g o] file name
List of octal numbers:
Example: $chmod 750 abc
It assign all permissions for user , read and execute for group and no permissions for
other for file abc.

cmp command
This command is used to compare files when used without options . It uses two
filename as an argument and display the difference on the terminals.
$cmp filename1 filename 2
$cat student1 $cat student2
Harsh Harsh
Sujay sujay
Smith smith
$cmp filename1 filename2
Student1 student2 diff : char 6 line 1

PROGRAM CODE :
1) Execute File and Directory Manipulation commands.

1. mkdir

2. cd

3. rmdir
4. pwd

5. diff command

6. comm command
7. ls –l

8. pr command

9. chmod command
a. Symbolic

b. Octal
10. cmp command

2) Create the following structure


PRACTICAL RELATED QUESTIONS :

1) How to shift from Root directory to User(Home) directory ?

Ans. We can shift from Root Directory to User(Home) directory by using : cd

2) How to see directories?


Ans. We can see directories using: dir

3) What is default set of permissions given by syetm to the directory?

Ans. Default permission for a directory is 0777, for files the permissions are 0666 from
which the default umask value 0022 is deducted to get the newly created files or directory
permission.

4) Assign all the permissions to your directory for all users using symbolic & octal methods.

Ans.

5) What is difference between comm and cmp command?

Ans.

Diff Command :

This command is used to show difference between two text files. It also tells which line in
one has to be changed to make the two files identical.

Syntax:

$diff filename1 filename2

The operations of the result should be like this –

a - Added the text to file

c - changes are made in the file

d - deletion operation is performed

< - lines from the first file

> - lines from the second file

Comm command :
This command compares two sorted files. It compares each line of first file with its
corresponding line in the second file and generates 3 column output.

The first column lists the lines only in first file.

The second column lists the lines only in second file.

The third column lists the lines in both files.

Syntax:

$comm filename1filename2

EXERCISE :
1. Write the commands for performing the following tasks sequentially

a. Display your current directory

b. Create a directory ‗subjects‘ in current directory

c. Create a file ‘sample’ in the directory ‘subject’

d. Remove the write permission for the owner for ‘sample’ using symbolic method

e. Delete the file ‘sample’. What is an error message displayed


No error displayed
2. What are the permissions assigned to file/files after execution of following commands?

Ans.

a. $chmod 700 abc


It assign all permissions for owner and no permissions for group & other for file
abc.

b. $chmod u+rwx,go-rwx file1 file2


It assign read, write, execute permissions for owner for file file1 and it removes read, write,
execute permissions for group & owner for file file2.

c. $chmod 536 xyz


It assign read and execute permissions for owner, write and execute permissions for group
and write and execute permissions for other for file xyz.

3. Create new files pqr & prql

Perform the commands

a. $chmod ugo=r pqr


Assign read the permission to all three users and removes all remaining permissions for file
pqr.
b. $chmod ugo+r pqrl
Assign read the permission to owner, group and other for file pqrl.

4. Assign read and write permission for the owner, write permission for the group and execute
permission for others using octal method for file mfile.

Ans.
5. Write commands to assign following permissions to file OSY using octal method
a. _ _ _ _ _ _ _ _ _ _
b. _rw_r_xr_ _
c. _r_xr_xr_x

Ans.

a. $chmod 000 OSY.txt

b. $chmod 654 OSY.txt

c. $chmod 555 OSY.txt

6. Write commands to assign following permissions to file OSY using symbolic method
a. _rwxr_xr_ _
b. _rwxrwxrwx

Ans.

a. $chmod u+rwx,g+rx,o+r OSY.txt

b. $chmod ugo+rwx

CONCLUSION : We successfully implemented file and directory manipulation commands


like mkdir, rmdir, cd, pwd ,dir, comm, diff, cmp, chmod etc.
Practical 8 : Execute text processing commands

PRACTICAL SIGNIFICANCE :
There are many text processing commands. A filter is commands that takes flow of data from the
standard input, process or filters it and sends the result to standard output. cut, wc, tr, sort or grep
are all simple filters.

MINIMUM THEORETICAL BACKGROUND :


PROGRAM CODE :
Execute text processing commands tr, cut, paste, wc, spell ,sort, grep, more

1) tr
2) cut

3) paste

4) wc
5) spell

6) sort
7) grep

8) more
PRACTICAL RELATED QUESTIONS :
1) Give the applications of paste commands
Ans. Paste command is one of the useful commands in Unix or Linux operating system. It is
used to join files horizontally (parallel merging) by outputting lines consisting of lines from
each file specified, separated by tab as delimiter, to the standard output.

2) How to move cursor at the end of line

Ans. Ctrl+E or End command can be used moves the cursor to the end of the line.

3) What are options of wc commands

Ans.

1. -l: This option prints the number of lines present in a file. With this option wc
command displays two-columnar output, 1st column shows number of lines present in a
file and 2nd itself represent the file name.
2. -w: This option prints the number of words present in a file. With this option wc
command displays two-columnar output, 1st column shows number of words present in a
file and 2nd is the file name.
3. -c: This option displays count of bytes present in a file. With this option it display
two-columnar output, 1st column shows number of bytes present in a file and 2nd is the
file name.
4. -m: Using -m option ‗wc‘ command displays count of characters from a file
5. -L: The ‗wc‘ command allow an argument -L, it can be used to print out the length of
longest (number of characters) line in a file. So, we have the longest character line
Arunachal Pradesh in a file state.txt and Hyderabad in the file capital.txt. But with this
option if more than one file name is specified then the last row i.e. the extra row, doesn‘t
display total but it display the maximum of all values displaying in the first column of
individual files
6. –version: This option is used to display the version of wc which is currently running
on your system.

4) What are different types of filters used in Linux

Ans.

 cat : Displays the text of the file line by line.


 head : Displays the first n lines of the specified text files. If the number of lines is
not specified then by default prints first 10 lines
 tail : It works the same way as head, just in reverse order. The only difference in
tail is, it returns the lines from bottom to up.
 sort : Sorts the lines alphabetically by default but there are many options
available to modify the sorting mechanism. Be sure to check out the man page to
see everything it can do
 uniq : Removes duplicate lines. uniq has a limitation that it can only remove
continuous duplicate lines(although this can be fixed by the use of piping).
Assuming we have the following data.
 wc : wc command gives the number of lines, words and characters in the data

5) What is difference between $cat abc and $cat abc more

Ans. Cat displays file contents. If the file is large the contents scroll off the screen before
we view it. So command 'more' is like a pager which displays the contents page by page.

EXERCISE :
1) Write the significance of following

I. Only one character is specified

$ paste -d "|" number state capital


1|Arunachal Pradesh|Itanagar
2|Assam|Dispur
3|Andhra Pradesh|Hyderabad
4|Bihar|Patna
5|Chhattisgrah|Raipur

II. More than one character is specified

$ paste -d "|," number state capital


1|Arunachal Pradesh,Itanagar
2|Assam,Dispur
3|Andhra Pradesh,Hyderabad
4|Bihar,Patna
5|Chhattisgrah,Raipur

First and second file is separated by '|' and second and third is separated by ','.After that
list is exhausted and reused.

III. -s(serials) ,combination of –d and –s ,-versions (write its syntax and example)
1) - s (serial):

Syntax :

$ paste -s number state capital

Example

1 2 3 4 5
Arunachal Pradesh Assam Andhra Pradesh Bihar Chhattisgrah
Itanagar Dispur Hyderabad Patna Raipur

2) Combination of -d and –s

Syntax :

$ paste -s -d ":" number state capital

Example

1:2:3:4:5
Arunachal Pradesh:Assam:Andhra Pradesh:Bihar:Chhattisgrah
Itanagar:Dispur:Hyderabad:Patna:Raipu

3) –version

Syntax :

$ paste –version

Example

paste (GNU coreutils) 8.26


Packaged by Cygwin (8.26-2)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

1. Create a new file and practice executing shell commands from within the editor.
Capture the results of some shell commands into file
K command= Move up one line.
Before using k command.

After using k command

X commands: Delete character to the left of the cursor

Before using X command

After using X command

l command= Move right one character


Before using l command.

After using l command

2. How to get help?


Ans. To get information about a single internal command, reading the entire shell
document is not only a time-consuming process but also a tedious task. Luckily, shell
offers a command, known as the help command

The help command uses the following syntax.

$help [options] [text-string/pattern/internal-command]

Example
2) Try the commands and write the outputs with its meaning

i. tr ―[a-f]‖ ―[1-5]‖ < employee

Output:

Meaning:

It can convert the letters from a-f to 1-5 in employee table

It starts from A=1 to E=5 in that file for conversion

ii. tr –s ― ‖ < employee

Output:
Meaning:

To squeeze repeat occurrences of characters specified in a set use the -s option. This
removes repeated instances of a character.

iii. tr –d ―f‖ < employee

Output :

Meaning:

To delete specific characters use the -d option. This option deletes characters in the first
set specified. In that f character deleted from it.

CONCLUSION : We successfully implemented text processing commands to perform


operations using commands like tr, cut, paste, spell, sort, grep, more, wc.
Practical 9 : Execute File and Directory Manipulation commands

PRACTICAL SIGNIFICANCE :
There are many ways to edit files in Unix. Editing files using the screen oriented text editor vi in
one of the best ways. This editor enables you to edit lines in context with other lines in the file.
Vi is intended as a plain text editor (similar to Notepad on Windows, or Textedit on Mac) as
opposed to word processing suite such as Word or pages. It does, however have a lot more power
compared to Notepad or Textedit.

MINIMUM THEORETICAL BACKGROUND :


Vi modes commands:

Command Action

K Move one line upwards


L Move one character to the right

H Move one character to the left

W Move one word to the right

W Move one word to the right past punctuation

B Move one word to the left

B Move one word to the left past punctuation

E Move to the end of the current word

1G Move to the beginning of the file

H Move to the top of the current screen

M Move to the middle of the current screen

L Move to the bottom of the current screen

Ctrl-G Move to the last line in the file

Ctrl-F Move one screen towards the end of the file

Ctrl-D Move 1/2 screen towards the end of the file

Ctrl-B Move one screen towards the beginning of the file

Ctrl-U Move 1/2 screen towards the beginning of the file

Ctrl-L Refresh the screen


5G Move to line 5 of the file (5 can be any line number)

/string Find text string forward

?string Find text string backward

N Find forward next string instance after a string search

N Find backward next string instance after a string search

ZZ Save the file exit vi

X Delete the character at the cursor

X Delete the character behind the cursor

Dd Delete the line the cursor is on

10dd Delete the 10 lines following the cursor

Yy Yank the current line

P Put the yanked line below the current line

P Put the yanked line above the current line

Commands mode commands:

Command Action

:g/X/s//x/g Global Search and replace (X=search object x=replace object)


:r file Import a file into the current file

:34 r file Import a file into the current file after line 34

:w Write out the file to save changes

:w file Write the file to named file

:wq Save the file exit vi

:w! Force save the file

:q! Quit vi but don‘t save changes

Input mode commands:

Command Action

A Insert characters to the right of the cursor

A Append characters to the current line

I Insert characters to the left of cursor

I Insert characters at the beginning of the current line

O Add a new line after current line

O Insert a new line above the current line


PROGRAM CODE :

Create a file OS and type at least 30 lines in it

1. Write the command to save the file.


Ans: To save the file and exit at the same time, you can use the ESC and :x key and hit
[Enter] . Optionally, press [Esc] and type Shift + Z Z to save and exit the file.

2. Write the command to insert text at the end of line.


Ans: Type A to add text to the end of a line. To see how this command works, position
the cursor anywhere on a text line and type A . The cursor moves to the end of
the line, where you can type your additions. Press Esc when you are finished.

3. Replace some character into beginning of second line.


Ans: :%s/ plus the text to find, another /, followed by the replacement text/

4. Write a command to delete 10 lines at a time.


Ans: :[start],[end]d
Example= :1,10d

5. Write a command to move cursor 3 words to the right.


Ans: To move right, press l (press 3 time).
I command Insert at cursor (goes into insert mode)

Create file command


File is created

K command= Move up one line.


Before using k command.

After using k command

j command = Move down one line


Before using j command.

After using j command


l command= Move right one character
Before using l command.

After using l command

h command= Move left one character

Before using h command


After using h command.

x command= Delete character at the cursor

Before using x command

After using x command


X commands: Delete character to the left of the cursor

Before using X command

After using X command


r command: Replace character at cursor with one other character

Before using r command

After using r command

yy command: Yank or copy line

P command: paste line


dd command: Delete line containing the cursor

Before using dd command

After using dd command

wq command Save changes and quit vi


q command Quit without saving changes

PRACTICAL RELATED QUESTIONS :


1. What is difference between Type o and type of O?

Ans:

Sr No o O

1 Creates a new line for text Creates a new line for text entry
entry below cursor location. above cursor location.

2 Command =o Command =O

2. State the three ways quit the vi editor.

Ans:

a. If you are currently in insert or append mode, press Esc .

b. Press : (colon). The cursor should reappear at the lower left corner of the
screen beside a colon prompt.

c. Enter the following: q!

3. What is effect of (type these at colon mode and observe the change in your fine)

Ans.

a. set nu

Line numbers will be displayed at the left side of the screen

b. set ic

Ignores the case when searching


c. set nonu
Hide line numbers

d. set noai

Unsets auto indent


4. Give vi command to delete line to the left of cursor.
Ans. Use Backspace to delete to the left of the cursor. If you need to move
the cursor to another line, or make a change, or pretty much anything else,
you need to press ESC to get back to Command mode first.

5. What is difference between young and delete?


Ans.
Sr No Young Delete
1 Copy is called yank ( y ) cut is called delete ( d )
2 Command =y Command =d

6. What are different modes in VI editor ?


Ans. Three modes of operation in vi are insert mode ,command mode. You use
insert mode to type text into a file, while command mode is used to type
commands that perform specific vi functions. Command mode is the
default mode for vi

1. Command mode: in this mode, you can open or create files, specify cursor
position and editing command, save or quit your work. Press Esc key to return
to Command mode.

2. Insert mode: In this mode, you can enter text into the display on your screen
to edit the file. To enter the Entry mode, you need to specify an input
command first. The input commands are: I for insert, o for overwrite, a for
append.

7. Observe the output of following commands:

i. at colon mode
:abbr MSBTE Maharashtra State Board of Technical Education
Now in the beginning of your find type MSBTE and press space bar write
down the output

ii. Go to beginning of your file press 4YY then move to end of your files and
press P write the purpose of the command.

Ans: 4yy is used to copy four lines and p is used to paste those lines

EXERCISE :
1. Write the significance of following
Ans.
i. $ vi temp.txt
vi will create the file ―temp. txt‖ for you. Save the file that you are in.
Create a file using vi editor and editing

ii. insert multiple lines


In visual block mode, you can press I to insert text at the same position in
multiple lines, and you can press A to append text to each line in a block. As
well as inserting or appending text that you type, you can insert or append text
from registers, for example, the clipboard.

iii. delete contents using command


It is important command .Which can be to delete line .We can delete multiple
lines at a time using this command.

2. Create a new file and practice executing shell command from which thing the
editor capture the result of some shell commands into the file

Ans. script file_nm


Execute commands
Run exit commands
cat file_nm

3. How to get help?


Ans.
a. Open vi editor.
b. Then click on help option.

CONCLUSION : So this practical was all about Vi editor. We have learned to create a new
file or open an existing one. we have also learned to insert, delete or remove the words from a
text file. In this practical, we run all the commands related to vi editor.
Practical 10 : Execute Shell Script by using if statement

PRACTICAL SIGNIFICANCE :
If is a statement that allows the programmer to make a decision in the program based on
conditions he specified. If the condition is met, the program will execute other task the
programmer specified.

MINIMUM THEORETICAL BACKGROUND :


The if…else…fi statement is the control statement that allows Shell to execute statement in
controlled way and make the right choice.
Syntax:
if [ expression ]
then
Statements(s) to be executed if expression is true
else
Statements(s) to be executed if expression is not true
fi
The shell expression is evaluated in the above syntax. If the resulting value is true, given
statement(s) are executed .If the expression in false, then no statement will be executed .
Relational operators are used along with if statement.
Relational Operator used by if:

Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal to

General Syntax:

1. Single Decision :-
Syntax:-
if [ condition ]
then
### series of code goes here
fi

2. Double Decision: -
Syntax:-
if [ condition ]
then
Statements if the condition is satisfied
else
Statements of code if the condition is not satisfied
fi

3. Multiple if Condition :-
Syntax:-
if [ condition1 ]
then
Statement for condition1
elif [ condition2 ]
then
Statements for condition2
else
Statements if the condition is not satisfied
fi

4. Double –Bracket :-
Syntax:-
if ((condition))
then
Statements goes here
fi

To type any program in Linux you need the compiler. vi editor is used for creating
file in Linux.
Write a shell script to display Welcome message with today‘s date in it. In vi editor
wright a program code and save and quit with filename‘sample.sh‘.
$vi sample.sh
(Now press escape and i to change the input mode and type following program)
#sample.sh
#use of if-then statement
if whoami; then
varl=‘whoami‘
echo ― Welcome $varl‖
fi
if date; then
echo ―It display todays date
fi
echo ―This is end of script‖
To run the script
$.sample.sh
Save this program press escape+shift+(colon) and type wq (:wq )
‖Welcome Userl‖
Mon Feb 25 22:29:29 PST 2019
―It displays todays date‖
―This is end of script‖

PROGRAM CODE :
Execute shell script by considering example to find passing grades of students using if
statement :

1. Single Decision

echo "Enter percentage here :"

read grade

if [ $grade -ge 90 ] && [ $grade -le 100 ]

then

echo "Grade A"

fi

if [ $grade -ge 70 ] && [ $grade -lt 90 ]

then

echo "Grade B"

fi

if [ $grade -ge 50 ] && [ $grade -lt 70 ]

then
echo "Grade C"

fi

if [ $grade -ge 35 ] && [ $grade -lt 50 ]

then

echo "Grade D"

fi

if [ $grade -lt 35 ]

then

echo "FAIL"

fi

Output :

2. Double Decision

echo "Enter percentage of Student : "

read grade

if [ $grade -gt 40 ]

then

echo "Pass"

else

echo "Fail"

fi

Output :
3. Multiple if statements

echo "Enter percentage of Student : "

read grade

if [ $grade -ge 90 ]

then

echo "Grade A"

elif [ $grade -ge 80 ]

then

echo "Grade b"

elif [ $grade -ge 70 ]

then

echo "Grade c"

elif [ $grade -ge 60 ]

then

echo "Grade d"

elif [ $grade -ge 40 ]

then

echo "Grade e"

else
echo "Grade Fail"

fi

Output :

PRACTICAL RELATED QUESTIONS :


1) Write and execute script for nested if statements.

Ans.

read -p 'username :' username

if [ "$username" == "abc" ]

then

read -p 'password :' password

if [ "$password" == "pwd" ]

then

echo "Login Successfully"

else

echo "Wrong Password"

fi

else

echo "Wrong Username"

fi

Output :
2) Write Difference between

Ans.

If[condition] If((condition))
The single brackets […] is the command . The double parentheses ((…)) is the format
for bash arithmetic expansion.
It is used to create commands in statements. It is used to test an arithmetic operations.
Syntax :- Syntax:-
if [ condition ] if((condition))
then then
### series of code goes here Statements goes here
Fi fi

Example :- Example:-
if [ ―$X‖-lt‖0‖ ] if [[ $num -eq 42 ]]
then then # if/then branch
echo ‖X is less then zero‖ echo 'num is actually equal to 42'
fi else # else branch
echo 'num is not 42'
fi

3) Write script for finding greatest number among given three number.

Ans.

echo "Enter number1 number : "

read n1

echo "Enter number2 number : "

read n2

echo "Enter number3 number : "

read n3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]

then

echo "$n1 is Greater"

elif [ $n2 -gt $n3 ]

then

echo "$n2 is Greater"

else

echo "$n3 is Greater"

fi

Output :

EXERCISE :
1) Correct the following script and write its output.

a. if [ ! –r ―$l‖ ] then echo ― File $l is not readable – skipping.‖; fi

Ans.

Error :

Program code:
read l

if [ ! -r $l ]

then

echo ―File $l is not readable – skipping.‖

fi

O
u
t
p
u
t

a. if [ ―$x‖ –nt ―/etc/passwd‖ ]; Then

echo ―X is file which is newer than /etc/passwd‖

if

Ans.

Error :

Program code:

read x

if [ $x -nt "/etc/passwd" ]

then

echo "$x is file which is newer than /etc/passwd"

fi
Output :

CONCLUSION : We successfully executed Shell Script by using if statements (Single


decision, Double decision, Multiple if condition)
Practical 11 : Execute Shell Script by using for statements

PRACTICAL SIGNIFICANCE :
The for loops iterate through a set of values until the list is exhausted. In simple terms the for
loop operates on lists of items. It repeats a set of commands for every item in a list.

MINIMUM THEORETICAL BACKGROUND :


Syntax of FOR loop :

for var in item1 item2…itemN

do

command1

command2

…. …

command

done

Example:

For var in 0 1 2 3 4 5 6 7 8 9

do

echo $var

done

So far you have looked at creating loops and working with loops to accomplish different tasks.
Sometimes you need to stop a loop or skip iterations of the loop. Following two statements that
are used to control shell loops.

Three-expression bash for loops syntax


This type of for loop can also be used similar to the C programming language. It is having by a
threeparameter loop control expression; consisting of an initializer (EXP1), a loop-test or
condition (EXP2), and a counting expression(EXP3).

Three-expression bash for loops syntax

A representative three-expression example in bash as follows:

#!/bin/bash

For((c=1;c<=5;c++)

do

echo ―Welcome Sc times‖

done

1. The break statements: The break statement is used to terminate the execution of the entire
loop, after completing the execution of all of the lines of code up to the break statement using
break keyword .
2. The continue statement: The continue statement is similar to the break command, except that
is causes the current iteration of the loop to exit, rather than the entire loop.
3. Exit:

The syntax is as follows:

exit N

The exit statement is used to exit from the shell script with a status of N.

Write a shell script to calculate the factorial of a given number.

In vi editor write a program code and save and quit with filename ‗fact.sh‗.

$vi fact.sh

(Now press escape and i to change the input mode and type following program)

Similar other loops also used in Linux such as while, case..esac

While statement

Syntax:

While[[condition]

do

Done

Example:

a=1

while[$a-le 5]

do

echo ―value of a=‖$a

a=‗expr$a+1‗

done

case..esac statement;

Syntax:

Case value in

pattern 1)commands;;

pattern 2)commands;;

pattern 3)commands;;

..

*)Default

esac //indication of end of case statement

Example:

#!/bin/bash

NOW=$(date+‖%a‖)

case $NOW in
Mon)

echo ―Full backup‖;;

Tue|Wed|Thu|Fri)

echo ―Partial backup‖;;

Sat|Sun)

echo ―No backup‖;;

*);;

esac

$cat fast.sh

echo ―Enter a number‖

read num

fact=1

while[$num-gt 1]

do

fact=$((fact*num))

num=$((num-1))

done

echo ―factorial of a numberis $fact‖

Save this program press escape+shift+:(colon)and type wq(:wq)

To compile the program

$./fact.sh or $sh fact.sh

Enter the number 5:

Factorial of a given number is 120

PROGRAM CODE :
1) Execute shell script by considering example like printing table of given number by FOR
loop

Ans.

read -p 'Enter no = ' no

echo "Table of $no"

for (( i=1; i<=10; i++ ))

do

echo " "$(( no * i ))

done

Output :

2) Execute shell script by considering example like printing

following output by FOR loop

******

****

**

Ans.

for (( i=1;i<8;i=i+2 ))
do

for (( j=1;j<7;j++ ))

do

if [ $i -le $j ]

then

echo -n "* "

else

echo -n " "

if [ $i -eq 7 -a $j -eq 5 ]

then

echo "*"

fi

fi

done

echo ""

done

Output :

PRACTICAL RELATED QUESTIONS :


1) Give output of the following a.
a.
#!/bin/sh
NUMBERS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q='expr $NUM % 2
if [ SQ -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done

Ans.

no="1 2 3 4 5 6 7"

for n in $no

do

q=$(( $n % 2 ))

if test $q -eq 0

then

echo "even"

continue

fi

echo "odd"

done

Output :
b. #!/bin/sh

a=0

while [ $a -lt 10 |

do

echo $a

if [ $a -eq 5 ]

then

break

fi

a=$(( $a + 1 ))

done

Output :

2) State the difference between Iteration and Recursion

Ans.

Property Recursion Iteration


Definition Function calls itself A set of instructions
repeatedly executed
Application For functions For loops
Termination Through base case, where When the termination
there will be no function call condition for the iterator
ceases to be satisfied
Usage Used when code size needs Used when time complexity
to be small and time needs to be balanced against
complexity is not an issue an expanded code size
Code Size Smaller code size Larger Code Size
Time Complexity Very high (generally Relatively lower time
exponential) time complexity complexity (generally
polynomial-logarithmic)

3) Write a shell script to display Fibonacci series for n numbers.

Ans.

read -p 'Enter no for fibonacci = ' no

x=0

y=1

no1=$no

while [ $no -gt 0 ]

do

z=$(( x + y ))

#echo $z

x=$y

y=$z

no=$(( no - 1 ))

done

echo "Fibonacci of $no1 is $y"

Output :

4) Write a shell script to display tables of 2 to 10 numbers

Ans.
5) Write a shell script to accept five digit number and to perform addition of all the digits.

Ans.

read -n 5 -p 'Enter 5 digit number: ' no

sum1=0

while [ $no -gt 0 ]

do

i=$(( no % 10 ))

sum1=$(( sum1 + i ))

no=$(( no / 10 ))
done

echo " Sum = $sum1"

Output :

EXERCISE :
Execute the script for the following

1) The for loop using day of week list

Ans.

for i in sun mon tue wed thur fri sat

do

echo $i

done

Output :

2) The while loop to print different * patterns.

Ans.
read -p 'Enter no for pattern = ' no

i=1

j=1

while [ $i -le $no ]

do

while [ $j -le $no ]

do

if [ $i -le $j ]

then

echo -n "* "

fi

j=$(( j + 1 ))

done

j=1

i=$(( i + 1 ))

echo ""

done

Output :
3) The case statements for performing various mathematical operations.

Ans.

read -p "enter 1st no" no1

read -p "enter 2nd no" no2

echo -e "1 add \n2 subtract \n3 multiply \n4 divide"

read -p "enter your choice " ch

case $ch in

1) c=$(( $no1 + $no2 ))

echo "addition = $c ";;

2) c=$(( $no1 - $no2 ))

echo "subtraction = $c ";;

3) c=$(( $no1 * $no2 ))

echo "multiplication = $c ";;

4) c=$(( $no1 / $no2 ))

echo "division = $c ";;

*) echo "invalid choice";;

esac

Output :
CONCLUSION : We are able to do different programs using shell script and vi editor.
And also we successfully implemented Shell Scripts.
Practical 12 : Write Shell Script to find out whether – Given file
exists?

PRACTICAL SIGNIFICANCE :
In UNIX data and programs are stored in file. These are organized in directories. In a simple
way, a directory is just a file that contains other files (or directories). It can be done to find out if
a file exists or not on the file system with the help of BASH shell and IF command.

MINIMUM THEORETICAL BACKGROUND :


This can be done by the shell script by using test conditions. Also if..else..fi statement is

used which allows us to make decisions based on the success or failure of a command.

Following is the list of the same flags which we can use in file list operators.

Shell Returns true if

-a file True if file exists.

-b FILE True if it is block special.

-c FILE True if it is character special.

-d file True if file exists and is a directory.

-e file True if file exists.

-f file True if file exists and is a regular file.

-s file True if file exists and has a size greater than zero.

Example:

#! /bin/bash

echo -e ― Enter the name of the file :‖

read file_name

if [-f file_name]
then

else

echo ―$file_name not exists‖

fi

Ordinary Files - An ordinary file is a file on the system that contains data text or

program instructions. In this tutorial, you look at working with ordinary file.

Directories - directories store both special and ordinary files. For users familiar with

Windows or Mac OS Linux directories are equivalent to folder.

Special File - Some special files provide access to hardware such a hard driver, CD

ROM driver, modems and Ethernet adapters. Other special files are similar to aliases or

shortcuts and enable you to access a single file using different names.

PROGRAM CODE :
Write a shell script which accepts input as a file or directory and displays message whether
it is file or directory.

echo "Enter file or directory name"

read file

if [ -f "$file" ]

then

echo "$file It is a file"

else

if [ -d "$file" ]

then

echo "$file It is a directory"

fi
fi

Output :

PRACTICAL RELATED QUESTIONS :


1) What is the command to run the script?

Ans. Run the script using ./<filename>

2) What are the file test options with its meaning?

Ans. The different file test operators are listed below :

 a : True if the file exists


 b : True if it is block special
 c : True if it is a character special file
 d : True if file exists and is a directory
 e : True if the file exists
 f : True if the file exists and is a regular file.
 g : True if the file exists and its SGID bit is set
 h : True if the file exists and is a symbolic link

3) What will be the output of these command (file =ABC.txt)


a. if [ ! -f ―$file‖ ]; then
echo ―$file‖
fi
b. test -f ―$file‖ || echo ― $file‖
c. [ -f ―$file‖ ] || echo ―$file‖

Ans.
EXERCISE :
1) Write a shell script to copy source file into the destination file.

Ans.

echo "Enter File name to copy \c"

read f1

echo "Enter file name \c"

read f2

if [ -f $f1 ]

then

cp $f1 $f2

else

echo "$f1 does not exist"

fi

Output :

2) Write a shell script which displays list of all directories in your home directory.

Ans.
echo "**Following are the directories of current directories**"

cd

ls -l |grep ^d

Output :

3) Write a shell script which displays list of all files in your home directory.

Ans.

echo "Enter directory name"

read dir

if [ -d $dir ]

then

echo "list of files in the directory"

cd $dir

ls

else

echo "Enter proper directory name"

fi

Output :
4) Write a file handling program. First check whether it is file or directory, then if it is file
the program shall ask user for choices of copying, removing and remaining files. Use
case statement.

Ans.

echo "enter file name"

read file

if [ -d "$file" ]

then

echo "it is directory"

else

echo "Enter your choice"

echo "1.copy file "

echo "2.rename file"

echo "3.remove"

read ch

case "$ch" in

"1") echo "Enter file name to be copied"

read cpfile

cp $file $cpfile

echo "File copied"

;;

"2") echo "enter name to rename "


read newname

mv $file $newname

echo "$file renamed as $newname"

;;

"3") rm $file

echo "removed "

;;

esac

fi

Output :
CONCLUSION : We have successfully completed shell script to find out whether given file
exists. In this practical we have studied checking if a file exists, the most commonly used FILE
operators are -e and –f
Practical 13 : Write shell script to check and grant permissions

PRACTICAL SIGNIFICANCE :
In Unix files come with permissions, a way to decide who can read, write or execute a file. These
permissions are divided into three parts: those for the owner (user) of the file, those for the group
to which the owner belongs and then permissions for all the other users from the point of view of
what is allowed to do in a file or directory, permissions are for reading, writing and executing.

MINIMUM THEORETICAL BACKGROUND :

Test Commands
Test Returns true if
-r file True if file exists and is readable.
-s file True if file exists and has a size greater than zero.
-w file True if file exists and is writable.
-x file True if file exists and is executable.

PROGRAM CODE :
Write a shell script to find out whether - File has read, write and execute permissions.

echo ―Enter the File : ‖

read line

if [ -r $line ]

then
echo ―$line has all the read permissions‖

fi

if [ -x $line ]

then

echo ―$line has all the execute permissions‖

fi

if [ -w $line ]

then

echo ―$line has all the write permissions‖

fi

Output :

PRACTICAL RELATED QUESTIONS :


1. What are permissions for a file?
Ans. Three permission sets are defined for each file object on a Linux system.
These sets include the read, write, and execute permissions for each of three
types of users—the owner, the group, and other users.

2. How to assign permission to a file?


Ans. Use the following procedure to change permissions in absolute mode.
a. If you are not the owner of the file or directory, become super user or
assume an equivalent role.
b. Only the current owner or super user can use the chmod command to
change file permissions on a file or directory.
c. Change permissions in absolute mode by using the chmod command

3. What happens when exception thrown by main() method.


Ans. When exception is thrown by main() method, Java Runtime terminates the
program and print the exception message and stack trace in system console.
The throws clause only states that the method throws a checked
FileNotFoundException and the calling method should catch or rethrow it

4. How to check permissions of all files and directories?


Ans. Check Permissions in Command-Line with Ls Command
If you prefer using the command line, you can easily find a file's permission
settings with the ls command, used to list information about files/directories.
You can also add the –l option to the command to see the information in the
long list

5. What are the test commands to check the permissions of a file?


Ans. The bash shell test command has many more options as follows:
-w FILE : FILE exists and write permission is granted.
-x FILE : FILE exists and execute (or search) permission is granted.
-d FILE : FILE exists and is a directory.
-e FILE : FILE exists.
-f FILE : FILE exists and is a regular file.

EXERCISE :
1) Write a shell script which displays the list of all executable files in the current working
directory

Ans.

pwd

ls > f

exec < f

while read line

do

if [ -f $line ]

then

if [ -x $line ]

then

echo ―$line‖
fi

fi

done

Output :

2) Write a shell script which displays a list of all the files in the current directory to which
user has read, write and execute permission.

Ans.

pwd

ls > f

exec < f

while read line

do

if [ -f $line ]

then

if [ -r $line –a –w $line –a –x $line ]

then

echo ―$line has all the permissions‖

fi

fi
done

Output :

3) Write a shell script which accepts a filename and assign it all the permissions.

Ans.

Echo ―ENTER THE FILE : ‖

Read file

Chmod u+xrw $file

Chmod o+xrw $file

Chmod g+xrw $file

Output :

CONCLUSION : We have successfully performed scripts to check and grant permission to


files.
Practical 14 : Implement Scheduling algorithms

PRACTICAL SIGNIFICANCE :
In Multiprogramming systems, the Operating system schedules the processes on the CPU to have
the maximum utilization of it and this procedure is called scheduling. The Operating System uses
various scheduling algorithm to schedule the processes. First come first serve (FCFS) scheduling
algorithm simply schedules the jobs according their arrival time.

MINIMUM THEORETICAL BACKGROUND :


In Multiprogramming systems, when there is more than one runnable process (i.e., ready), the
operating system decides which one to activate. The decision is made by the part of the operating
system called the scheduler, using a scheduling algorithm. CPU scheduling selects the processes
from memory that are ready to execute, and allocates the CPU to one of them.

PROGRAM CODE :
Consider the processes P1, P2, P3, P4 given in the below table, arrives for execution in
the same order, with Arrival Time 0, and given Burst Time, Find using the FCFS
scheduling algorithm.

1. Turn Around Time for each process.

2. Waiting Time for each process.

3. Average Turn Around time.

4. Average waiting time.

Process Burst Time


P1 21
P2 6
P3 3
P4 2

#include<stdio.h>
#include<conio.h>
int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("\nEnter Total Number of Processes(maximum 20):");
scanf("\n%d",&n);
printf("\n enter process burst timen");
for(i=0;i<n;i++)
{
printf("\nP[%d]:",i+1);
scanf("\n%d",&bt[i]);
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}
printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time:");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
}
avwt/=i;
avtat/=i;
printf("\n\nAverage Waitng Time: %d",avwt);
printf("\nAverageTurnaround Time: %d",avtat);
return 0;
}
Result/Output :

PRACTICAL RELATED QUESTIONS :


1. Compare SJF, Priority and RR with respect to turnaround time and average waiting
time.
Ans.
SJF RR Priority

1.Turnaround time is 1.turnaround time is 1. Turnaround time


more than FCFS. more than Priority. is less than RR.

2.Average waiting 2.The average waiting 2.In this scheduling


time for given set of time for given set of algorithm the
processes is processes is quite small average waiting
minimum. and depends on the time time is small as
quantum. compare to FCFS.

2. State the conditions for preemptive and non-preemptive scheduling algorithm.


Ans.
Conditions for preemptive and non-preemptive scheduling algorithm:-
 When a process switches from the running state to the waiting state(for example,
I/O request, or invocation of wait for termination of one of the child processes).
 When a process switches from running state to the ready state (for example, when
an interrupt occurs).
 When a process switches from the waiting state to the ready state (for example,
completion of I/O).
 When a process terminates.

3. Give the reason of problems arises in FCFS.


Ans. The reason behind this is, in time sharing operating system it is necessary that each
user should get CPU share after certain interval. It would be terrific to allow one process
to keep the CPU for long time.

4. Write a formula for turnaround Time.


Ans. Turnaround Time= Ending Time - Arrival Time

5. Write a formula for Average waiting Time.


Ans. Average waiting Time =
Waiting time of p1+ waiting time of p2+ …+waiting time of pN / No. of processes.

EXERCISE :
1. Draw the Gantt chart for above mention example.

Process Burst Time


P1 21
P2 6
P3 3
P4 2

Gantt chart:
P1 P2 P3 P4
0 21 27 30 32

2. Calculate average waiting time using RR algorithm for following set of processes
with the length of the CPU burst time given in milliseconds. ( Time quantum 20 ms ).
Process Burst Time
P1 12
P2 45
P3 78
P4 90

P1 P2 P3 P4 P2 P3 P4 P2 P3 P4 P3 P4 P4

0 12 32 52 72 92 112 132 137 157 177 195 215 225


Waiting Time :

P1=0

P2=12+(72-32)+(132-92)=92

P3=32+(92-52)+(137-112)+(177-157)=117

P4=52+(112-72)+(157-132)+(195-177)+(215-215)=135

Average Waiting Time:

0+92+117+135 ÷4 = 344÷4= 86

3. The jobs are scheduled for execution are as follows:


Solve the problem using FCFS and Preemptive SJF find average waiting time using
Gantt chart.
Process Arrival Time Burst Time
P1 0 10
P2 1 4
P3 2 14
P4 3 8

1) FCFS
Gantt Chart:
P1 P2 P3 P4
0 10 14 28 36

Waiting time

P1=0
P2=10-1=9

P3=14-2=12

P4=28-3=25

Average Waiting Time = 0+9+12+25÷4=46÷4=11.5 msec

2) Pre-emptive SJF:

Gantt chart:

P1 P2 P4 P1 P3
0 1 5 13 22 36

Waiting Time:

P1=12

P2=1-1=0

P3=22-2=20

P4=5-3=2

Average Waiting Time: 12+0+20+2÷4=34÷4= 8.5 msec

CONCLUSION : We successfully implemented scheduling algorithms to find waiting time


and turnaround time with their averages. Also we understood the differences between these
algorithms.
Practical 15 : Write a ‘C’ program to implement FIFO page
replacement algorithm

PRACTICAL SIGNIFICANCE :
When there is a page fault, the referenced page must be loaded. If there is no available frame in
memory, then one page is selected for replacement. if the selected page has been modified, it
must be copied back to disk (swapped out). A page replacement algorithm is needed to decide
which page needs to be replaced when a new page comes in.

MINIMUM THEORETICAL BACKGROUND :


This is the simplest page replacement algorithm.in this algorithm operating system keeps track of
all pages in the memory in a queue, oldest page is in the front of the queue. when a page needs to
be replaced page in the front of the queue is selected for removal.

PROGRAM CODE :
#include<stdio.h>

int main()

int i,j,n,a[50],frame[10],no,k, Flag,count=0;

printf("\n ENTER THE NUMBER OF PAGES:\n");

scanf("%d",&n);

printf("\n ENTER THE PAGE NUMBER :\n");

for(i=1;i<=n;i++)

scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");

scanf("%d",&no);

for(i=0;i<no;i++)

frame[i]= -1;

j=0;

printf("\tref string\t page frames\n");

for(i=1;i<=n;i++)

printf("%d\t\t",a[i]);

Flag =0;

for(k=0;k<no;k++)

if(frame[k]==a[i])

Flag=1;

if (Flag==0)

frame[j]=a[i];

j=(j+1)%no; //inc pos

count++;

for(k=0;k<no;k++)

printf("%d\t",frame[k]);

printf("\n");

printf("Page Fault Is %d",count);


return 0;

getch();

Result/Output :
PRAC
TICAL
RELA
TED
QUES
TIONS
:

1) State the advantages and disadvantages of FIFO.


Ans.
Advantages of FIFO :-

1. FIFO method is easy to understand and operate.


2. FIFO method is useful where transactions are not voluminous and prices of materials are
falling.
3. FIFO method is suitable for bulky materials with high unit prices.
4. FIFO method helps to avoid deterioration and obsolescence.
5. Value of closing stock of materials will reflect the current market price.

Disadvantages of FIFO:-

1. FIFO method is improper if many lots are purchased during the period at different
prices.
2. The objective of matching current costs with current revenues can not be achieved
under FIFO method.
3. If the prices of materials are rising rapidly, the current production cost may be
understated.
4. FIFO method overstates profit especially in inflation.
2) What is page hit ?
Ans. If CPU tries to retrieve the needed page from main memory, and that page is existed in
the main memory (RAM), then it is known as PAGE HIT.

3) What is page fault ?


Ans. A page fault (PF or hard fault) is a type of exception raised by computer hardware
when a running program accesses a memory page that is not currently mapped by the
memory management unit (MMU) into the virtual address space of a process.

4) count number of page hits in above mention example given in section x


Ans. Total page hits = 6

EXERCISE :
1) Consider reference string 9,7,6,1,7,6,1,2,7,2 the number of frames in the memory is 3.
Find out number of page faults and page hit respective to

d. Fifo Page replacement algorithm

Ref string Frames


9 9
7 9 7
6 9 7 6
1 1 7 6
7
6
1
2 1 2 6
7 1 2 7
2
Total page faults : 6
Total page hits : 4

2) Compare FIFO and LRU.

FIFO LRU
FIFO I First in First Out LRU is Least Recently Used
Number of page fault is more than LRU Number of page fault is less than FIFO
Suffer from belady‘s anomaly Does not suffer from belady‘s anomaly
Simple to implement Considered to be good

CONCLUSION : We gained knowledge about various page replacement algorithms and


successfully implemented FIFO page replacement algorithm.

You might also like