Вы находитесь на странице: 1из 100

Department of Computer Engineering

Prepared By

Vijay T. Patil
1
A Laboratory Manual for

Operating Systems
(22516)

Semester - V

Diploma in Computer Engineering Group

2
Vidyalankar Polytechnic

CertifiCate

This is to certify that

Mr/Ms…………………………………………………………………………
Roll No………………………. of Fifth Semester of Diploma in
Computer Engineering of Institute
Vidyalankar Polytechnic (Institute Code: 0568 / 1090) has
completed the Term Work satisfactory in Course Operating
Systems (22516) for the Academic Year
…………………….………………..
As prescribed in the Curriculum.

Place:……………………….. Enrollment No:……………………


Date:………………………… Seat No……………………………….

Subject Teacher Head of Department Principal


3
List of Experiments and Progressive Assessment for Term Work

Academic Year:…………………….…… Name of Faculty……………………..……..…

Course and Code:…………………..…. Subject and Code:…………..……………….

Name of Candidate:…………………………………………..…………………………………..

Enrollment No……………………………..……. Roll No…………………………………….


Sr. Title of Experiment Date of Date of Assessment Sign. Of
No. Performance Submission Mark out Teacher
of 50
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 Use Operating system
services (Editor, GUI, File
handling)
Run commands to start,
stop, and restart the
specified service 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
redirection operator),
head, tail, touch.

4
Sr. Title of Experiment Date of Date of Assessment Sign. Of
No. Performance Submission Mark out Teacher
of 10
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 editor commands.
10 Write and execute shell
script by using following
control statement
features – “if” statement.
11 Write and execute shell
script by using following
control statements
features – “for”
statement, exit, break,
continue.
12 Write shell script 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.

5
Assessment Scheme
Performance Indicators (15 Marks) Weightage
Process related (15 marks) 30 %
1 Logic formation 10 %
2 Debugging Ability 10 %
3 Follow ethical practices 10 %
Product related (35 Marks) 70 %
4 Expected Output 30 %
5 Timely Submission 30 %
6 Answer to sample Questions 10 %
100 %

6
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 01
Title of Experiment Install and configure Linux (or alike) operating system.
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the concept of installation and booting
procedure

Marks Obtained Dated Signature of Teacher


Process Related Product Related Total
(15) (35) (50)

7
Practical Significance: Linux is the base of many of open source operating systems designed to replace
Windows and Mac OA. It is free to download and install on any computer. Because it is open source,
there are a variety of different versions or distributions, available developed 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 at large.

Steps to install Ubuntu:


Step:1 Download the ISO file
Once the iso file has been downloaded, burn it into DVD or USB drive and make it bootable.

Step:2 Boot your system with Bootable DVD / USB drive.


To start the installation click on “Install Ubuntu”

Step:3 Check Install Prerequisite


Make sure you have at least 6.6 GB free disk space and if you want to download updates and third
party tools at the installation, check both the boxes and make sure system is connected to Internet
 Download updates while installing
 Install this third-party software

8
click on Continue….
Step:4 Select the Installation Type
If your system has new hard drive and if nothing installed on it, then you can choose the first option
“Erase disk & Install Ubuntu”.
If you want LVM based file system, then use third option “Use LVM with new Ubuntu Installation”
If you want to create customize partition table, the use last option “Some else”

Click on Install Now….


Confirm to Write Changes to Disk

click on Continue….

9
Step: 5 Select your respective Time Zone

Step:6 Select your respective Keyboard Layout

Click on Continue…

10
Step:7 Set the Hostname of your system and User credentials that will be used after installation.

Click on Continue….
Step:7 As shown below Installation has started.

11
Once the installation is completed, it will ask to restart the Machine.

Click on “Restart Now”


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

12
Ubuntu 15.04 Installation is Completed Now.
Similarly any open source installation shall be considered.

Practical Related Questions


1. What are different versions of Linux Operating system
OS Version
Ubuntu 18.10
Red Hat 8
Open SUSE 15.1
Linux Mint 18.1
Fedora 17
Arch Linux 5.1
Kali Linux 5

2. State names of latest multiuser operating system and its advantages


Names the multiuser operating system
 Ubuntu
 macOS
 Unix
 IBM AS400
 Windows 10
 All Linux based OS

13
Advantages of Multiuser Operating system
Using multi-user operating system, we can perform multiple tasks at a time, i.e. we can run more
than one program at a time. Example: we can edit a word document while browsing the internet
 Printing jobs in the office or library can be best handled by multi user operating system. Normal
OS cannot do the same job as printing can be mismatched.
 Each user can access same document on own pc. For example, if one computer has a song or
movie then other computers attached with it will play that song or movie on their pc also.
 Airlines also use this system and ticket reservation is also done by this system.
 Teachers and library staff also use multi user operating system for handling books and for
searching books. The book record is stored in one computer and other terminals access to
single resource to query the books.
 If one computer in the network gets error, then other computers not get affected and that
system handle this efficiently.

Exercise
1. Differentiate between command line OS and GUI based OS by giving example
Command Line Interface Graphical User Interface
It is a text-based interface used to interact with It is a visual-based interface which features the
software and operating system by typing use of graphic images, including Windows,
commands into the interface and receive a Icons, and Menus.
response in the same way.
CLI is faster and difficult to use than GUI. GUI is slower and easier to use than CLI.
CLI consumes low memory. It consumes high memory.
Not much flexible. GUI is more flexible.
Commands need to be remembered to be able Commands need not be remembered as they
to type and execute them. can be executed by simply clicking on icons.
CLI is less user friendly. GUI is more user friendly.
Examples: DOS, Unix etc. Example: Windows, Linux etc.

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


 Multiprogramming increases CPU utilization by organizing jobs such that the CPU always has
one to execute. In multiprogrammed systems the operation system keeps several jobs in
memory at a time. This set of jobs is a subset of the jobs kept in the job pool.
 The operating system picks and begins to execute one of the jobs in the memory. Eventually
the job may have to wait for some task, such as a tape is mounted, or an input/output operation
to complete.
 In a non-multiprogramming system, the CPU would sit idle. In a multiprogramming system, the
operating system simply switches to and executes another job. When that job needs to wait,

14
the CPU is switched to another job and so on. Eventually the first job finishes waiting and gets
the CPU back. As long as there is always some job to execute, the CPU will never be idle.

Advantages of multiprogramming systems


 It increases CPU utilization. CPU is used most of time and never become idle
 The system looks fast as all the tasks runs in parallel
 Short time jobs are completed faster than long time jobs
 Resources are used nicely
 Total read time taken to execute program/job decreases
 Response time is shorter
 In some applications multiple tasks are running and multiprogramming systems better handle
these type of applications
Disadvantages of multiprogramming systems
 It is difficult to program a system because of complicated schedule handling
 Tracking all tasks/processes is sometimes difficult to handle
 Due to high load of tasks, long time jobs have to wait long

3. Which are the extra facilities provided by Unix other than windows OS
Unix OS Windows OS
No License fee, free of cost Required license fee, expensive
Open source Not open source
More secure Less secure
Unix is a Command Line User Interface Windows is Graphic User Interface Operating
system
Not even driven Windows is event driven
Not support plug and play Windows operating system support plug and
play
File system in Unix is (STD.ERR,STD.IO) File system in Windows is (FAT32,NTFS).

15
4. Enlist four features of following operating system
Window-98
 Protection: Windows 98 includes additional protection for important files on your computer
such as backing up your registry automatically.
 Improved support: Improved support for new devices and technologies such as ACPI, AGP, IEEE
1394, DVD, USB, and MMX.
 FAT32: Windows 98 has the capability of converting your drive to FAT32 without losing any
information.
 PnP: Improved PnP support, to detect devices even better than Windows 95.
 Internet Explorer 4.0: Includes Internet Explorer 4.0
 Customizable Taskbar: Windows adds new features to the Taskbarsuch as Quick Launch that
Windows 95 and Windows NT did not have.
 Includes Plus!: Includes features only found in Microsoft Plus! free.
 Active Desktop: Includes Active Desktop that allows for users to customize their desktop with
the look of the Internet.
 New background properties: You can now set *.bmp, *.pcx, *.jpg, *.gif, and *.htm files as
your wallpaper (background).
 Updated Microsoft Paint: The updated paint allows you to open *.bmp, *.pcx, *.jpg, and *.gif
files.
 Multiple monitor support: Windows 98 now supports multiple monitors on one computer.
 Personal Web Server: PWS supports CGI (common gateway interface) and ISAPI (Internet
Server Application Programming Interface) applications.
 Improved floppy drive: Includes HSFLOP.PDR floppy disk driver that helps speed up access for
many floppy disk drives.
 Other Software: Includes Dr. Watson, Outlook Express, FrontPage Express, Windows Media
Player, DirectX, NetMeeting, and more.

Windows-2000
 Active Directory: Microsoft included Active Directory feature for the first time in Windows
2000 Server. Active Directory is used to store information about resources, users, or a group
and its attributes.
 Distributed File System: Windows 2000 server operating system brought Distributed File
System (DFS) feature which enables users to distribute files across multiple servers over the
network.
 NTFS 3.0 File system: Windows 2000 Server introduced new version of NTFS file system i.e.
NTFS 3.0 with new features such as file-system-level encryption, disk quotas, sparse files and
reparse points.
 Virtual Private Network: This operating system provides virtual private network feature that
allows you to make your computer a remote server and enables other users to connect to the
server via VPN. With this feature, users can access shared files that reside on your system or
on the network.
 Encrypted file systems protect sensitive data.
 Multilingual version allows for User Interface and help to switch, based on login.
 Includes broader support for high-speed networking devices, including native ATM and cable
modems.
 Supports USB (Universal Serial Bus) and IEEE 1394 for greater bandwidth devices.

16
Windows-XP
 Remote Desktop Windows XP professional OS enables user to use remote desktop connection
feature means they can sit at a PC and access another PC remotely.
 Device Driver Rollback: This new Windows XP feature let users uninstall installed device driver.
If users install device driver that causes system instability, then they can easily roll back the
previous driver.
 Built-in CD burner When Windows XP arrived, it came up with its own in-built CD burner
feature. Now there is no longer need to install CD burning software, user can burn files directly
via Windows Explorer.
 Encrypted file system support multi-user: This feature is for Windows XP Professional,
encrypted file system make it possible to access encrypted files and folders by multiple users.
 Device support improvement: Windows XP supports USB 2.0, Intel High Definition Audio based
hardware, FireWire, & Windows Image Acquisition based scanners etc.

17
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 02
Title of Experiment Execute general purpose commands date, time, cal,
clear, banner, tty, script, man
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the use of basic purpose commands

Marks Obtained Dated Signature of Teacher


Process Related Product Related Total
(15) (35) (50)

18
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 a shell program.

Theoretical Background
Commands Description
date It displays system date and time
cal Displays calendar for current month
clear Clears the screen
banner Displays an argument string as a poster with maximum of ten characters per
line
tty Name of terminal
script Record login session
man It gives manual help for any command

Proposition-1: date command


The date command is used to print and set the date.
Syntax:
date [−u] [+ format]
date [−u] [MMDDHHmm [YY] −t[[CC]YYMMDDhhmm.[SS]]
Example:
$ date
Tue Aug 28 15:00:21 EST 2003
$_
The command can also be used arguments. Each format is preceded by a ‘+’ symbol, followed by ‘%’
operator and a single character describing the format if you can print only month using the format
‘+%m’.
$ date +%m
8
$_
or month name
$ date +%h
Aug
$_
or combine them in one command
$ date +”%h %m”
Aug 28
$_
Formatted output for data command
Field Descriptor Function
%a Abbreviated weekdays (SUN to SAT)
%A Full weekday name
%b Abbreviated month name (JAN to DEC)
%B Full month name
%c Current date and time
%C Century (00 to 99)
%d Day of month 0 to 31
%D Day as MM/DD/YY
%e Day of month as decimal number
19
%h Abbreviated month
%H Hour 00 to 23
%I 01 to 12 (12 hour clock)
%j Day of the year 001 to 366
%m Month of the year 01 to 12
%M Minute 00 to 59
%n New line
%p Am / pm
%r Time in AM/PM notation
%T Time in hh:mm:ss (24 hrs clock)
%y Last two digit of year
%Y Year (in four digit)

Proposition-2: cal command


Cal command is used to display the calendar of any month or year. Any calendar from the year 1 to
9999 can be displayed with this command.
Syntax:
$ cal [[month] year]
Generally cal command prints a calendar for the specified year.
Example:
$ cal 2000

Apr. May Jun.


----- ----- -----
----- ----- -----

Jul. Aug. Sep.


----- ----- -----
----- ----- -----

Oct. Nov. Dec.


----- ----- -----
----- ----- -----
If a month is specified then it displays calendar of that month.
$ cal 01 2003
jan
s m tu w th f s
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
20
The cal command is accurate and also takes into account the leap year adjustments that took place in
the year 1752.
Option Description
-1 Display single month output
-3 Display prev / current / next month output
-s Display Sunday as first day of week
-m Display Monday as first day of week
-j Display julian dates
-y Display a calendar for current year

Proposition-3: clear Command


clear is a standard Unix command which is used to clear the screen.
It clears the screen
Syntax:
$ clear

Proposition-4: banner command


This command displays it argument like poster, with maximum of 10 characters per line.
$ banner HELLO
# # ##### # # #####
# # # # # # #
##### ### # # # #
# # # # # # #
# # ##### ##### ##### #####

Proposition-5: tty command


Since Unix treats even terminals as files, it is reasonable to expect a command which tells you the
device name of the terminal you are using. As there is different file for each terminal, all these files are
placed in the ‘/dev’ directory. It is the tty (teletype) command; reference to the device, which has now,
becomes absolute. The command is simple and needs no arguments.
Syntax:
tty [option]...
Example:
$ tty
/dev/tty01
$_
The output displays the complete pathname.

Proposition-6: script command


Script makes a typescript of everything printed on your terminal. It is useful for students who need a
hardcopy record of an interactive session as proof of an assignment, as the typescript file can be
printed out later with lpr. Script is used to take a copy of everything which is output to the terminal
and place it in a log file. If the argument file is given, script saves all dialogue in file If no file name is
given, the typescript is saved in the file named typescript.
Example:
vtp@VTP:~$ script
Script started, file is typescript
vtp@VTP:~$date
Tue Dec 13 19:50:35 IST 2016
21
vtp@VTP:~$who
vtp tty7 2016-12-13 19:22
vtp@VTP:~$exit
exit
Script done, file is typescript

Proposition-7: man command


To access this online manual, use the man command.
Syntax:
man [section_number] page title
Example:
$man sort
This command would display the pages of the manual that have all the description for the sort
command.

Practical Related Questions:


1. How you record all the following activities performed by the user
Sol: We record all the activities performed by the user using script command

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


Sol: cal 1 2019

3. Give single statement command to display the calendar of previous, current and next month
Sol: cal -3

4. Give command to display full week day (e.g. Sunday) using data command
Sol: date “+%A”

Exercise:
1. what is output of following commands?
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)
i. This is ……………….. month of the year ……….. (Abbreviations for month and 4-digit year)
ii. This is the ……..’th day of this year

22
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 03
Title of Experiment Work with multiple Linux terminals and basic
commands: who, who am I, login, passwd, su, pwd
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the use of basic purpose commands

Marks Obtained Dated Signature of Teacher


Process Related Product Related Total
(15) (35) (50)

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

Theoretical Background:
Command Description
who It is used to display who are the users connected to out computer currently.
who am i Display the details of the current working directory.
login Prompt; enter user name
passwd Sets password for users
su (sudo) Provides super user privileges
pwd To print the complete path of the current working directory.

Proposition-1: who command


Unix is a multi-user environment. Unix maintains an account of all the current users of the system. It
is good idea to know the people working on the various terminals so that you can send them messages
directly. Who command displays the information of all the users currently logged in the system along
with their terminal number and the time of login.
$ who
kumar tty01 jan 30 14:09
tiwari tty02 jan 30 14:15
sharma tty03 jan 30 13:20
$_
By default, who command produces a three columnar output. There are three users of the system,
with their login name in first column. The second column shows the device name of their respective
terminals. The third column shows the data and time of logging in.
The –h (header) option prints the column headers.
$ who
Name Line Time
kumar tty01 jan 30 14:09
tiwari tty02 jan 30 14:15
sharma tty03 jan 30 13:20
$_
Option Function
-b Indicate the time and date of the last reboot.
-d Print dead processes
-H print line of column headings
-l Print system login processes
-m Only host name and user associated with stdin
-p print active processes spawned by init
-q all login names and number of users logged on
-r Print current run level
-u list users logged in.

Proposition-2: who am i command


The who command when used with the arguments am i, displays a single line of output only i.e. the
login details pertaining to the user who invoked this command.
$ who am i
kumar tty01 jan 30 14:09
24
$_

Proposition-3: login
If the user has a password login print password. If password is correct then it allows to enter in login
user is successfully logged into the Unix system.
Only those persons who maintain on “account” with the computer system can use the Unix system.
This list of account is maintained separately in the computer. Ask the administrator of the system to
open an account for you. You start an allotted terminal when you see the following message on the
screen
login:
login: vijay <enter>
if a password has been allotted to you the system will flash the following message.
password:
After confirm password it displays $ prompt. The $ prompt (currency symbol) is the system prompt,
which indicate to the user that some user is logged in and that the system is ready to accept any
command from him. Some of system displays different prompts – the % or # for instance.

Proposition-4: passwd command


You can start your system by changing the password, using a command named passwd.
$passwd <enter>
old password: --- <enter>
new password: --- <enter>
re-enter password: --- <enter>
$_
passwd is in Unix jargon called a command a Unix command. There are several such commands in
the system.

Proposition-5: su (sudo) command


The linux command su is used to switch from one account to another. User will be prompted for the
password of the user switching to.
$ su abc
Password:
abc@VTP:~$
User can also use it to switch to root account. If user types only ‘su’ without any option then it will be
considered as root and user will be prompted to enter root user password.
vtp@VTP:~$su
Password:
root@VTP:/home/vtp#

Proposition-6: pwd command


You can always find out the directory where you are currently placed by using the pwd (present
working directory) command. When user logged into the unix system, unix automatically places the
user in the home directory. The name of home directory is a login name itself. If the user is working in
login with username “kumar” his home directory is /usr/kumar or /home/kumar
$ pwd
/usr/kumar
$_

25
The pwd command resembles the cd command of MS-DOS when used without argument. Thus pwd
tells you that your current directory is /usr/kumar, you can refer to a sub directory progs, either as
/usr/kumar/progs or simply as progs.

26
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 04
Title of Experiment a) Use operating services, Run commands to start
stop and restart the specified service in Linux
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the use of basic purpose commands for
services

Marks Obtained Dated Signature of Teacher


Process Related Product Related Total
(15) (35) (50)

27
Practical significance: The purpose of computer systems is to allow the user to execute programs. So
the operating systems 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 system.

Proposition-1: Start, stop, and restart the given services in Linux


The init process on Linux systems is commonly known as the mother of all processes. The "init" process
will always have a Process ID of "1" (pid of 1), it is the first process started by the kernel on your system.
init is short for initialization and is used to start all other processes and your default run level. Overtime
many distributions have adopted the System V standard for managing services, however, other
distributions have moved to "Systemd" or "Upstart".
Generally, in Linux dedicated servers, there are two different kind of programs running, one which
needs user interaction and another which execute tasks without user involvement. The programs that
execute tasks in the background are normally known as “services” and “daemons”. Basically, there are
many services required on servers to run the background such as DB Server, Firewall, Web Server, DNS
System, Mail Server, etc… Due to these various services, it is very much essential to know the exact
procedure of starting, stopping and restarting the services.
Administrator can stop, start, restart or reload a particular service/daemon. To do this we use a
command called "service". This command allows you to execute "System V" scripts that are normally
located within the "/etc/init.d" directory. As well as being able to start and stop a service/daemon, we
can also view the current status.

Check the status of all processes in Linux:


$ service –status-all
vtp@VTP:~$ service --status-all
[ + ] acpid
[ - ] anacron
[ - ] apparmor
[ ? ] apport
[ + ] atd
[ + ] avahi-daemon
[ + ] bluetooth
[ - ] brltty
[ ? ] console-setup
[ + ] cron
[ + ] cups
[ + ] cups-browsed
[ - ] dbus
….
….

To start the Service:


We requesting the anacron should be started:
vtp@VTP:~$ sudo service anacron start
anacron start/running, process 3434
vtp@VTP:~$ service --status-all
[ + ] acpid
[ + ] anacron
28
[ - ] apparmor
[ ? ] apport
[ + ] atd
[ + ] avahi-daemon
[ + ] bluetooth
[ - ] brltty
[ ? ] console-setup
[ + ] cron
[ + ] cups
[ + ] cups-browsed
[ - ] dbus
….
….

To stop the service:


Here we requested that the "anacron" daemon should stop.
vtp@VTP:~$ sudo service anacron stop
anacron stop/waiting
vtp@VTP:~$ service --status-all
[ + ] acpid
[ - ] anacron
[ - ] apparmor
[ ? ] apport
[ + ] atd
[ + ] avahi-daemon
[ + ] bluetooth
[ - ] brltty
[ ? ] console-setup
[ + ] cron
[ + ] cups
[ + ] cups-browsed
[ - ] dbus

To restart the service:


Here we are going to "bounce" the "anacron" daemon (stop and then immediately restart).
vtp@VTP:~$ sudo service anacron restart
anacron stop/waiting
anacron start/running, process 3833

29
Q. What is difference between GUI and CLI
Sol:
Command Line Interface Graphical User Interface
It is a text-based interface used to interact with It is a visual-based interface which features the
software and operating system by typing use of graphic images, including Windows,
commands into the interface and receive a Icons, and Menus.
response in the same way.
CLI is faster and difficult to use than GUI. GUI is slower and easier to use than CLI.
CLI consumes low memory. It consumes high memory.
Not much flexible. GUI is more flexible.
Commands need to be remembered to be able Commands need not be remembered as they
to type and execute them. can be executed by simply clicking on icons.
CLI is less user friendly. GUI is more user friendly.
Examples: DOS, Unix etc. Example: Windows, Linux etc.

Exercise:
1. What are system calls provided by file management
Sol: file related system call:
 Create file, Delete file
 Open a file, Close a file
 Create directory
 Read, Write, Reposition
 Get file attributes, Set file attributes
 Create a link
 Change working directory

2. Draw and explain services provided by operating system


Sol:
 Program Execution: system capability to load a program into memory and to run it.
 I/O operations: since user programs cannot execute I/O operations directly, the operating
system must provide some means to perform I/O.
 File-system manipulation: program capability to read, write, create, and delete files. Maintain
details of files or directories with their respective details.
 Communications: exchange of information between processes executing either on the same
computer or on different systems tied together by a network. Implemented via shared memory
or message passing.
 Error Detection: ensure correct computing by detecting errors in the CPU and memory
hardware, in I/O devices, or in user programs.
 Resource Allocation: allocating resources to multiple users or multiple jobs running at the same
time. Coordinating among peripherals.
 Accounting: keep track of and record which users use how much and what kinds of computer
resources for account billing or for accumulating usage statistics.
 Protection: ensuring that all access to system resources is controlled.
 Security: Providing protection to program, data, and files and to ensure data security.

30
3. What are system component of operating system
Sol:
 Process management
 Memory management
 I/O management
 File management
 Communication
 Protection and Security

31
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 05
Title of Experiment Execute process commands – ps, wait, sleep, exit, kill
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of process related commands.

Marks Obtained Dated Signature of Teacher


Process Related Product Related Total
(15) (35) (50)

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

Theoretical Background:
Command Description
ps Display the characteristics of process.
wait Waits until all background processes are completed and then exits.
sleep 30 Used to execute commands after certain amount of time by sleeping for given
seconds.
exit Used to quit the shell.
kill 0 Used to stop execution of particular process by sending an interrupt signal to
the process.

Proposition-1: ps command
 A process is simply an instance of a running program.
 The process is said to be born when the program starts execution, and remains alive as long as
the program is active. After the execution of the program is complete, the process is said to
die.
 This process also has a name; the name of program being executed.
 Unix is multi-tasking system; more than one process can run at a time. Each process is uniquely
identified by a number called the PID (the process identifier ) which is allotted by the kernel
when it is born. This is a number between 0 and 32,767.
 The ps command is used to display the characteristics of a process. The command invoked
without options simply lists out the processes associated with a user at a particular terminal:
Syntax: ps [option]
$ ps
PID TTY TIME COMMAND/cmd
30 01 0:03 sh
56 01 0:00 ps
$_
Each line shown the PID, the terminal with which the process is associated, the cumulative processor
time that has been removed since the process has been started and the process name. Your login shell
has PID number 30. The ps command itself is an instance of a process identified by PID number 56.

PS command Options
Parameter Description
-a Displays all processes except session headers and processes without a terminal.
-c Displays additional scheduler information about the process.
-d Displays all processes except session headers.
-e Displays all processes.
-f Displays a full format listing.
-j Displays job information.
-l Displays a long listing.
-w Use wide output format, for unlimited width displays
-y Don’t show process flags.
-A Displays all processes.
-F Use extra full output.

33
-H Display processes in a hierarchical format (showing parent processes).
-L Displays process threads
-M Display security information about the process.
-N Displays the opposite of the specified parameters.
-U userlist Displays processes owned by a userid listed in userlist .
-V Display the version of ps
-Z Display the security context information.

The ps command by default does not provide details about the ancestry of a process. To get those you
have to use the –f (full) option:
$ ps -f
UID PID PPID C STIME TTY TIME COMMAND
Kumar 30 1 0 11:18:08 01 0:03 -sh
Kumar 61 30 13 11:24:01 01 0:00 ps -f
$_
The full listing generates eight attributes of a process.
 UID: User ID
 PID: The process ID of the process
 PPID:The PPID (parent PID) is the PID number of the parent process that spawned this process.
Login shell has PID number 1610 and PPID number 1603. Thus the shell was set up by a system
process having a PID number 1.
 C: Indicates the amount of CPU time consumed by the process.
 STIME: start of process time.
 TTY: The terminal device from which the process was launched
 TIME: The cumulative CPU time required to run the process
 CMD: The name of the program that was started

The –u (user) option lets you know the activities of any user at any time.
$ ps –u Vijay
PID TTY TIME COMMAND
31 pts/2 0:02 sh
59 pts/2 0:00 grep
60 pts/2 0:16 sort
$_
you also combine the –f and –u options:
The –a (all) option lists out the processes of all users:
$ ps –a
PID TTY TIME CMD
1718 pts/0 00:00:00 ps
161 pts/1 00:00:02 sh
354 pts/2 00:00:12 grep
246 pts/1 00:00:37 sh
360 pts/2 00:00:01 ps
439 pts/1 00:00:00 sh
440 pts/3 00:00:01 awk
$_
$ ps –p 533
PID TTY TIME COMMAND
533 pts/1 0:01 vi
34
$ ps –l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 1610 1603 8 80 0 - 1858 wait pts/0 00:00:00 bash
0 R 1000 1665 1610 0 80 0 - 1193 - pts/0 00:00:00 ps
$_
Attributes of –l options
 F: System flags assigned to the process by the kernel.
 S: The state of the process (O = running on processor; S = sleeping; I=idle process; X: process
waiting for memory; R = runnable, waiting to run; Z = zombie, process terminated but parent
not available; T = process stopped)
 UID: The user responsible for launching the process
 PID: The process ID of the process
 PPID: The PID of the parent process (if a process is started by another process)
 C: Processor utilization over the lifetime of the process
 PRI: PRI shows the priority with which the process is running. (higher numbers mean lower
priority)
 NI: The nice value, which is used for determining priorities
 ADDR: ADDR shows the memory or disk address of the process.
 SZ: The size of process is memory is indicated by the SZ column.
 WCHAN: When process is executed, it may have to wait for system resources which are not yet
available. This indication is shown under WCHAN for running processes this column is blank.
 TTY: The terminal device from which the process was launched
 TIME: The cumulative CPU time required to run the process
 CMD: The name of the program that was started

Proposition-2: wait command


wait: wait is a built-in shell command which waits for a given process to complete, and returns its exit
status. wait waits for the process identified by process ID pid (or the job specified by job ID jobid), and
reports its termination status. If an ID is not given, wait waits for all currently active child processes,
and the return status is zero. If the ID is a job specification, wait waits for all processes in the job's
pipeline.
Syntax: wait pid
Example: wait 2112
Wait for process 2112 to terminate, and return its exit status.

Proposition-3: Sleep command


sleep: The sleep command is used to delay for a specified amount of time. The sleep command pauses
for an amount of time defined by NUMBER. SUFFIX may be "s" for seconds (the default), "m" for
minutes, "h" for hours, or "d" for days.
Syntax: sleep NUMBER[suffix]
Example: sleep 10
Delay for 10 seconds.

Proposition-4: exit command


exit: The exit command terminates a script, just as in a C program. It can also return a value, which is
available to the script's parent process. Issuing the exit command at the shell prompt will cause
the shell to exit.
Syntax: exit

35
Proposition-5: kill command
 The kill command will kill a process using the kill signal and PID given by the user.
 The kill command allows you to send signals to processes based on their process ID (PID).
 The command uses one or more PID numbers as its arguments.

Syntax:
kill [signal] PID
Kill pid1 pid2 ….

Example: To terminates the job with the PID number 105.


$ kill 105

Options of kill command


Option Description
Kill 0 Kills all the processes on the terminal except the login shell by special
argument 0
Kill 120 230 250 Kill three processes with pid 120 230 250
Kill -9 0 Kill all processes including login shell
Kill -9 $$ Kills login shell

Practical related questions:


1. What is process id of your login shell
Sol: $echo $$

Exercise:
$ sleep 30; date
$ echo $$
$ sleep 60; banner “Goog”

36
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 06
Title of Experiment Execute file and directory manipulation commands:
ls, rm, mv, cp, join, split, cat, head, tail, touch
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of file manipulation commands.

Marks Obtained Dated Signature of Teacher


Process Related Product Related Total
(15) (35) (50)

37
Practical Significance
Basically the operating performs I Unix/Linux are done on prompt/terminal which is not stored
anywhere. But most of the commands are written to store the information. One way is to store the
information in a file. Various operations that can be performed on a file are create, open, read, write,
move, close and rename.

Proposition-1: ls command
The ls command displays a list of files which are available in directory.
$ ls <enter>
chap1
chap2
chap3
$_
Options of ls commands :

Option Description
-a Displays all files including ., .. and hidden files
-A Displays all but not . and .
-C List entries by column
-d List directory entries instead of contents
-l Use ling listing format
-r Sort in reverse order
-R List subdirectory recursively
-s Prints size of each file in blocks
-S Sort by file size
-t Sort by modification time
-u Sort by access time
-V Sort by version
-1 List one file per line
-X List in column format with row wise sorting
-F Classifies files, executables, directories
-i Shows inode number of a file
Example:
$ ls –l chap1
-rwxr--r-- 1 user1 group1 712 jan 20 10:30 chap1

(file mode) (no. of links) (file owner) (group name) (size of file) (date& time) (file name)

Proposition-2: rm command
Deleting files – The rm command:
Files can be deleted with rm (remove). The following command deletes the first three chapters of the
text.
$ rm chap1 chap2 chap3
$_
rm won’t normally remove a directory, but it can remove files from one.
$ rm progs/chap1 progs/chap2
you can remove two chapters from progs directory without having to “cd” to it.
You can easily delete all files in directory by
38
$ rm *
$_

MS-DOS users beware! When you delete files in this fashion, the system won’t prompt you with the
message “Are you sure?” or “all files in directory will be deleted?” before removing the files. The $
prompt will return silently, suggesting that the work has been done. When rm is invoked with
options, different things start happing. The –i (interactive) option makes the command prompt the
user with each filename and a?, before acting on it:
$ rm –i chap1 chap2 chap3
chap1 : ? y
chap2 : ? n
chap3 : ? n
$_
if you press ‘y’ then the file will be deleted.

Option Description
-f Ignore non-existant files, and never prompt before removing.
-i Prompt before every removal.
-I Prompt once before removing more than three files, or when removing recursively.
Less intrusive than -i, while still giving protection against most mistakes.
-r Remove directories and their contents recursively.

Proposition-3: mv command
The mv (move) command simply renames a file or a group of files. mv does not create a copy of file,
it merely renames it.
To rename the file chap1 to man1
$ mv chap1 man1
$_
$ mv chap1 chap2 chap3 progs
$_
moves the files chap1, chap2 and chap3 to the progs directory. mv can be used to rename a
directory.
Option Description
-f Do not prompt before overwriting existing files.
-i Prompt before overwriting each existing destination file, regardless of the
file's permissions.
-n Do not overwrite any existing file.

Proposition-4: cp command
Coping a File – The cp command:
 The cp (copy) command copies a file or a group of files.
 If the command contains two file names, then it copies the contents of first file to the second
file. If the second file doesn’t exist, then first is creates one and content is copied to it, but if it
existed then it is simply overwritten without any warning.
 Similar to copy command of MS-DOS, cp creates an exact images of the file on the disk with a
different name. To copy the file chap1 to unit1 you use
$ cp chap1 unit1
$_
39
If there is only one file to be copied, then the destination can be either an ordinary or a directory file.
For example to copy file chap1 to directory progs.
$ cp chap1 progs/units
$_
If there are groups of files to be copied, then you specify command line: the syntax requires the
destination file to be a directory and copies the files into directory.
$ cp chap1 chap2 chap3 progs

Proposition-5: join command


Join utility is used to combine data from tables that contain related information. A file can be created
using join by matching rows from two tables based on the field that is common to both.
$ cat file1
101 45 60
102 50 62
103 63 75
104 44 50
$ cat file2
101 79 43
102 43 54
103 65 55
104 99 80
$_
join –t option is used to specify the field separator.

$ join –t “|” file1 file2


101 | 45 | 60 | 79 | 43
102 | 50 | 62 | 43 | 54
103 | 63 | 75 | 65 | 55
104 | 44 | 50 | 99 | 80
$_

Proposition-6: split command


Splitting a file - The split command
The split command is used to divide a single large file into several ones. The file is split into smaller
files with equal number of lines in each file.
Syntax: split –n file outfile
The file is split into lines of 1000 by default. Each file is named with xaa, xab, xac appended to it and
so on lexicographically upto zz. If no output is given x is default. By integer n the number of lines in
the output file can be controlled.
$ split –4 file1
$ ls
xaa
xab
xac
$_

file1 has 12 lines is split into three files xaa, xab, xac of 4 lines each or
$ split –4 file1 num
The file “file1” of 12 lines is split into three files numaa, numab, numac of 4 lines each.

40
Proposition-7: cat command
Displaying and Creating files- The cat command
The cat command like the type command of MS-DOS, cat is used to display the contents of file. To
do that for the file dept.lst, simply specify the filename as the argument:
$ cat dept.lst
01 | computer | 60
02 | information | 40
03 | electronics | 60
$_

cat also accepts more than one filename as arguments.


$ cat chap1 chap2
The contents of the second file are shown immediately after the first file without any message or
header information.
Cat is normally used for displaying text files only.
cat is also useful for creating a file.
Enter the command cat, followed by the ‘>’ character and the filename
( for example abc) and press the <enter> key. Enter text messages and then press <control-D>:
$ cat > abc
This is simple text file.
hello
<control-D>
$_
cat is also useful for appending the contents at the end of file
$ cat >> abc
Text is enter at the end of file
<control-D>
$_
$ cat abc
This is simple text file.
hello
Text is enter at the end of file
$_

Proposition-8: head command


Displaying the Beginning of a file - The head command
The head command, as the name implies, displays the top of the file. By default, you can only read
first ten lines of a file.
Syntax:
head <option> <filename>
$ head emp.lst
You can change the number of lines displayed by specifying a number option as shown below:
$ head -20 temp
It displays first 20 lines of a file.

41
Proposition-9: tail command
Displaying the end of a file - The tail command
The tail command displays the end of the file. If no line count is given, tail displays the last ten lines
of the file.
$ tail emp.lst
$_
syntax : $ tail [ + - ] number [file]
option Description
-n Display specified number of lines
+n Display all lines beginning from nth line
$ tail -20 temp It displays last 20 lines of a file
$ tail +20 temp it displays lines from line number 20 to end of file

Proposition-10: touch command


Touch command creates new but empty files
$ touch sample
$ touch a1 a2 a3

Exercise:
1. Create three files a1 a2 a3
2. Display all file names which starts with ‘a’ and end with ‘y’
3. Enlist all the files beginning with ‘m’ and ending with any range of 1 to 5
4. Show the contents of the files whose file names contains exactly two characters
5. How many lines will be displayed with head command if number is not specified
6. Display inodes of two files
7. Rename the file chapter1 to lesson1
8. ls a*n
9. ls s?
10. cat abc >> xyz

42
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 07
Title of Experiment Execute file and directory manipulation commands:
diff, comm, pr, chmod, mkdir, rmdir, cd, pwd, dir,
cmp. (use wild card characters)
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of file manipulation commands.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

43
Practical Significance
Data and programs are stored in files. Directory is just a file that contains other files (or directories).
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, slash character(/).
All files in UNIX are “related” to one another. The file system in UNIX is a collection of all these related
files organized in a hierarchical (an inverted tree) structure. This system has been adopted by MS-DOS
and is visually represented by:

UNIX file System

The top is called root, but is represented by a / (backslash). Root is actually a directory file, and it has
a number of sub-directories (or branches) under it. Home, bin and usr are directories directly under
root while a second mthomas and stu1 are sub directories under home. Every file apart from root must
have a parent home directory is a parent of stu1, while root is parent of home, bin usr, and the
grandparent of stu1. Once the relationship between various files is established in this manner, UNIX
provides a simple mechanism of accessing a file. The login directory mthomas can also be specified as
/home/mthomas. It is called a pathname for the directory file mthomas. Every pathname consists of
a sequence of directory names separated by /’s. The tree like structure enables you to create as many
directories as you wish so that one directory does not need to contain too many files. This permits you
to use two files with the same name but in different directories, so that they will have different
pathnames. Thus the file /home/mthomas/class_stuff/a1.c is different from the file
/home/mthomas/bin/a1.c
Most Unix commands use files whether you should use the command cat xyz.c to display the
contents of the file. The directory where you are placed or located is known as the current directory.
The directories shown directly under root are normally found in every UNIX system. The directories
/bin, /dev, /etc and /lib are system directories and the other directories like /tmp and /usr are meant
for the users.
The commonly used UNIX commands like who. cat, wc, etc are stored in the /bin and /usr/bin
directories and made available to every user. /dev contains the device files of all hardware devices.
/etc contains those utilities mostly used by the system administrator. /tmp is used by some UNIX
utilities (especially vi) as well as by a user to store temporary files. Finally, the /usr directory contains
all the files created by a user including his login directory.
The directories in UNIX operating system have specific purposes and generally hold the same types of
information for easily locating files. Following are the directories that exist on the major versions of
UNIX:

44
Directory Description
/ This is the root directory which should contain only the directories needed at the top
level of the file structure.
/bin This is where the executable files are located. They are available to all user.
/dev These are device drivers.
/etc Supervisor directory commands, configuration files, disk configuration files, valid user
lists, groups, ethernet, hosts, where to send critical messages.
/lib Contains shared library files and sometimes other kernel-related files.
/home Contains the home directory for users and other accounts.
/mnt Used to mount other temporary file systems, such as cdrom and floppy for the CD-
ROM drive and floppy diskette drive, respectively
/proc Contains all processes marked as a file by process number or other information that is
dynamic to the system.
/boot Contains files for booting the system.
/sbin Contains binary (executable) files, usually for system administration. For example fdisk
and ifconfig utlities.
/tmp Holds temporary files used between system boots
/usr Used for miscellaneous purposes, or can be used by many users. Includes
administrative commands, shared files, library files, and others
/var Typically contains variable-length files such as log and print files and any other type of
file that may contain a variable amount of data
/kernel Contains kernel files

Proposition-1: mkdir command


Making a Directory – The mkdir command:
The mkdir command just as in MS-DOS, directories can be created by using the mkdir (make
directory) command. The command is followed by the names of the directories to be created.
Syntax: mkdir <directory name>
$ mkdir chap1
$_
unlike MS-DOS, however a number of sub-directories can be created by one mkdir command:
$ mkdir lesson lesson/chap1 lesson/chap2
This creates three sub directories lesson and two subdirectories.

Proposition-2: cd command
Changing Directories – The cd command
You can move around in the file system by using the cd (change directory) command. It changes the
current directory to the directory to the directory specified as the argument.
Syntax: cd <directory name>
$ pwd
/usr/kumar
$ cd progs
$ pwd
/usr/kumar/progs
$_

45
Proposition-3: rmdir command
Removing a Directory – The rmdir command:
The rmdir (remove directory) command removes or deletes directories.
Syntax: rmdir <directory name>
$ rmdir lesson
$_
you can not delete a directory unless it is empty. The three directories and the sub directories that
were just created with mkdir can be removed by using rmdir with a reversed set of arguments.
$ rmdir lesson/chap1 lesson/chap2 lesson

Proposition-4: dir command


To get a list of all the files and folders in the current directory use the dir command.
Option Description
-a To show hidden files. when you run the command in this fashion that it lists a file
called . and another called .. The first dot signals the current directory and the
two dots signal the previous directory.
-A do not list implied . and ..
-C list entries by columns
-i print the index number of each file
-l Use a long listing format
-S sort by file size
-r reverse order while sorting
-R list subdirectories recursively
-1 list one file per line

Proposition-5: pwd command


Checking your current directory – The pwd command:
You can always find out the directory where you are currently placed by using the pwd (present
working directory) command. When user logged into the unix system, unix automatically places the
user in the home directory. The name of home directory is a login name itself. If the user is working in
login with username “kumar” his home directory is /usr/kumar or /home/kumar
$ pwd
/usr/kumar
$_
The pwd command resembles the cd command of MS-DOS when used without argument. Thus pwd
tells you that your current directory is /usr/kumar, you can refer to a sub directory progs, either as
/usr/kumar/progs or simply as progs.

Proposition-6: diff command


diff is the third command which can be used to display the differences. It produces a detailed output.
$ cat file1
shukla p.k.
chanchal singh
s.n.dasgupta
chakroborthy
$_
$ cat file2
barun sengupta
46
shukla p.k.
anil agrawal
chowdhary
s.n.dasgupta
$_
$ diff file1 file2
oal
> barun sengupta
2c3, 4
-------
> anil agarwal
> chakroborthy
$_
the instruction oa1 indicates that a single line has to appended after line number 0 of the first file
and the resultant line will have line number 1 and 2nd file.

Proposition-7: comm command


Comm compares two sorted files and compares each line of the first file with its corresponding line in
the second. Its displays a three columnar output. The first column contains lines unique to the first file,
while the second column shows the lines unique to second file. The third column displays lines
common (hence its name) to both files.
$ cat file1
shukla p.k.
chanchal singh
s.n.dasgupta
chakroborthy
$_
$ cat file2
barun sengupta
shukla p.k.
anil agrawal
chowdhary
s.n.dasgupta
$_

$ comm file1 file2


barun sengupta
shukla p.k.
anil agrawal
chanchal singh
chowdhary
s.n.dasgupta
chakroborthy
$_
first column contains two entries i.e. the lines common only to file1 (chanchal singh and chakroborthy)
while second column shows three, you can see that shukla p.k. and s.n.dasgupta, who are present in
both files, have been displayed in the third column.
comm can also produce selective output using the option –1, -2 and –3.

47
To drop a particular column simply use its column number with the –sign. Thus to select only those
lines which are not common to both files you should exclude the third column from the output:

$ comm –3 file1 file2


barun sengupta
anil agrawal
chanchal singh
chowdhary
chokroborthy
$_
you can also combine option and display only those lines which are common:
$ comm –1 2 file1 file2
shukla p.k.
s.n.sengupta
$_

Proposition-8: cmp command


Comparing two files - The cmp command
Frequently you may require to know whether two files are identical in all respects so that one of
them can be deleted. The cmp (compare) command is used to achieve this task.
$ cmp chap1 chap2
chap1 chap2 differ : char 9, line1
$_

The two files are compared byte by byte and the location of the first mismatch is echoed to the
screen. If the two files are identical then cmp displays no message, but simply returns the $ prompt.

The –l (list) option gives detailed list of the byte number and the differing bytes in octal for each
character that differs in both the files.
$ cat file1
abcd
xyz
$ cat file2
abed
wxy
$_

$cmp –l file1 file2


3 143 145
6 170 167
7 171 170
8 172 171
$_

Proposition-9: pr command
File formatting and printing commands-pr command:
The pr command prepares a file for printing by adding suitable headers, footers and formatted text.
$ pr dept.lst
May 11 10:17 1990 dept.lst page 1

48
01 | 2233 | shulka a.k. | g.m. | sales | 6000
02 | 9876 | Sharma | director | production | 7000
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_
pr adds five lines of margin at the top and five lines at the bottom of the five lines at the top one is
reserved for header information. The header shows the date and time of the last modification of the
file along with the filename and page number.
$ pr dept.lst | lp
request id is 334
$_

pr also accepts input from standard input which can also be redirected to originate from a file.
$ pr < dept.lst
May 11 10:17 1990 dept.lst page 1
01 | 2233 | shulka a.k. | g.m. | sales | 6000
02 | 9876 | Sharma | director | production | 7000
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_
by default the page size is 66 lines which is the size used in U.S.A. however continuous stationary is
also available with 72 lines on each page. Use –l (length) option along with a numeric argument to
specify that:

$ pr –l 72 chap1
The option –l 72 sets the page to 72 lines of which to lines (5+5) will be used by the top and bottom
margin leaving 62 for the actual contents of the file. The option –w (width) which overrides the
default width of 72 characters.
$ pr –w 132 chap1
you can also frame your own header instead of displaying filename by using –h (header) option:

$ pr –h “code List” dept.lst


May 11 10:17 1990 code List page 1
01 | 2233 | shulka a.k. | g.m. | sales | 6000
02 | 9876 | Sharma | director | production | 7000
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_
Lines can also be numbered with the –n (number) option.
$ pr –n –h “code list” dept.lst
May 11 10:17 1990 code List page 1
01 | 2233 | shulka a.k. | g.m. | sales | 6000
02 | 9876 | Sharma | director | production | 7000

49
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_

The –k option (where k is any integer) produces output in more than one column across the page.
$ pr –3 dept.lst
May 11 10:17 1990 code List page 1
01 | shulka a.k. 02 | Sharma 03 | charkrobarty
04 | sengupta 05 | gupta n.k. 06 | patel
<blank lines>
$_
The –d (double) option double spaces the output i.e. it adds a blank line for every line read.
$ pr –172 –w80 –n –d dept.lst

The –m (merge) option allows you to merge two or more files simultaneously so that they appear
pasted laterally.
$ pr –m dept.lst sal.lst
you can omit header and footer with the –t option.
$ pr –m –n –t dept.lst sal.lst

Proposition-10: chmod command


Set Permission using chmod
The chmod command is used to change access permissions to files and directories. The chmod (change
mode) command is used to set the permission of one or more files for all three categories of users
(user, group and others). There are two ways to change the file permissions:
 Relative Permission
 Absolute Permission
Relative permission: When changing permissions in a relative manner, chmod only changes the
permissions specified in the command line and leaves the other permission unchanged.
Syntax: Chmod category operations permission filename(s)
Abbreviations used by chmod:
Category Operation Permission
u – User + assign permission r- read permission
g – Group - remove permission w- write permission
o - Other = assign absolute permission x – execute operation
a – All
Example:
$ ls -l Note
-rw-r--r-- 1 vtp vtp 0 Jun 16 15:20 Note
$ chmod ugo+x note
$ ls –l Note
-rwxr-xr-x 1 vtp vtp 0 Jun 16 15:20 Note
$_

50
Absolute Permission (The Octal Notation):
In absolute permission, each type of permission is assigned a number. This format requires specifying
permissions using three octal numbers ranging from 0 to 7. The octal code can be one to three digits
long. The first, second, third digits set the “user” “group” “other” user permissions respectively. The
integer used in each position dictates the permission for the file.

Linux File Permission Codes


Permissions Binary Octal Description
--- 000 0 No permissions
--x 001 1 Execute-only permission
-w- 010 2 Write-only permission
-wx 011 3 Write and execute permissions
r-- 100 4 Read-only permission
r-x 101 5 Read and execute permissions
rw- 110 6 Read and write permissions
rwx 111 7 Read, write, and execute permissions

Concept Diagram:

Example: $ chmod 750 sample


This example changes access permission for the file sample in the current working directory. The ‘7’
gives read, write and execute permission for owner. The ‘5’ gives read and execute permission for
group and ‘0’ gives no permission for other users.

Exercise
1. Create the following structure

51
2. How to see directories
3. What is default set of permissions given by the system to the directory
4. Assign all the permissions to your directory for all the users using symbolic and octal method
5. What is difference between comm and cmp command
6. What are the permissions assigned to file after execution of following commands
a. $ chmod 700 abc
b. $ chmod u+rwx,go-rx file1
c. $ chmod 536 xyz
d. $ chmod ugo=r abc
e. $ chmod ugo+r abc
7. Write commands to assign following permissions to the file “abc” using symbolic method and octal
method
a. _ _ _ _ _ _ _ _ _
b. _ rwr_xr_ _
c. rwxrwxrwx
d. r_ _ r_ _ _ _ _
e. rwxr_xr_x
f. rwxrw_rw_

52
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 08
Title of Experiment Execute text processing tr, wc, cut, paste, spell, sort,
grep, more
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of text processing commands.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

53
Practical Significance: There are many text processing commands. A filter is a program that takes a
flow of data from the standard input, processes or filters it and send the result to standard output.
Cut, wc, tr, sort, grep are all simple filters.

Proposition-1: tr command
Translating characters - The tr command
Syntax : tr <option> <expressions1> <expression2> <standard input>
The first difference that this command takes only the standard input as the source of its data; it does
not take a filename as its argument. When invoked without options, it translates each character in
expression1 to its mapped counterpart in expressions2. The first character in the first expression is
replaced by the first character in the second expression and similarly for the other characters.
The following tr command is used to convert the lower case to upper case
$tr
Operating system
OPERATING SYSTEM
The following command will also convert lower case to upper case
$ tr [:lower:] [:upper:]
ops
OPS

More Examples
1) $ tr “[a-z]” “[A-Z]” < xyz or ( ‘a-z’ ‘A-Z’)
$ tr “[:lower:]” “[:upper:]” < xyz
used to fold all lowercase characters to uppercase in the file xyz
2) $ tr “[a-d]” “[0-3]” < xyz
first four lowercase alphabets are substituted with numbers from 0-3
3) $ tr –s “ “ < xyz
squeezes all occurrences of blank spaces to one space in the file xyz
4) $ tr –d “e” < xyz
deletes all occurrences of e from file xyz
5) $ tr –cd “e” < xyz
all characters other than e would be deleted from the file xyz
6) $ tr –c “[a-z]” “[\n]” < file1
outputs a list of all words in file1, one per line in file2

Proposition-2: wc command
 The wc (word count) command in Unix/Linux operating system is used to find out number of
lines, words and characters in a file.
 Unix features a universal word counting program. The command name is in fact a misnomer: it
counts lines, words and characters depending on the options used. It takes one or more
filenames as its argument and displays a four columnar output.
Syntax: wc [-l-w-c] <filename>
Options Description
-l Counts only number of lines
-w Counts only number of words
-c Counts only number of characters

54
Example:
$ cat data1
wc command counts characters,
words and lines
$_
$ wc data1
2 7 45 data1
$_
we counts 2 lines, 7 words, 45 characters. A line is group of characters. A word is group of characters
not containing a space, tab or newline. A character is smallest unit of information and includes all
spaces, tabs and newlines. The filename has also been shown in the fourth column. wc offers three
options to make a specific count. –1 counts only number of lines, -w and –c options counts words
and characters respectively.
$ wc –1 data
2 data
$ wc –w data
7 data
$ wc –c data
45 data
$_

When wc is used with multiple filenames, it produce a line for each file as well as total count.
$ wc chap1 chap2 chap3
305 4058 23179 chap1
550 4732 28132 chap2
377 4500 25221 chap3
1232 13290 76532 total
$_

Proposition-3: cut command


Slitting a file vertically - The cut command
 It is used to copy the specified columns to the standard output file. It is used to cut portion of
a file. It takes filenames as command line argument or input from standard input. It does not
delete the selected portion of a file.
 While head and tail are used to slice a file horizontally you can slice a file vertically with the
cut command. Cut identifies both columns and fields and is a useful filter for the programmer.
Syntax: cut <option> <character or field list> <file(s)>
$ cat shortlist
2233 | shulka a.k. | g.m. | sales | 6000
9876 | Sharma | director | production | 7000
5678 | charkrobarty | d.g.m. | marketing | 6000
2365 | sengupta | director | personnal | 7800
5423 | gupta n.k. | chairman | admin | 5400
$_
cut can be used to extract specific columns from the file ex. Name (second field) and designation
(third field). The name starts from column number 6 and goes up to column no. 22, while designation
data occupies columns 24 through 32. use –c (column) option for cutting columns:

55
$ cut –c 6-22, 24-32 shortlist
2233 shulka a.k.
9876 Sharma
5678 charkrobarty
2365 sengupta
5423 gupta n.k.
$_
column numbers must immediately follow the option.
$ cut –f 1, 5 shortlist
2233 | 6000
9876 | 7000
5678 | 6000
2365 | 7800
5423 | 5400

option Function
-f Displays the fields specified
-c Cutting of columns i.e. character by character
-d Specifies the column delimiter

Proposition-4: paste command


Pasting files - The paste command:
The paste command 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.
When no file is specified, or put dash (“_”) instead of filename, paste reads from standard input and
gives output as it is until a interrupt command (Ctrl-c) is given.
Paste command is used to paste several files together.
$ cat f1
11
12
13
$cat f2
AA
BB
CC
DD
EE
$ paste f1 f2
11 AA
12 BB
13 CC
DD
EE
$paste –s f1 f2
11 12 13
AA BB CC DD EE
$_

56
Proposition-5: spell command
spell is a spell-checking program which scans a text file for misspelled words, and prints each
misspelled word on its own line. spell is a very minimalistic spell-checking program, based on the
original UNIX spell checker. It reads the contents of file FILE, word for word, checking them against its
dictionary. If a word does not correspond with any of spell's dictionary words, the word is printed.
Syntax: spell [OPTIONS] FILE
Options:
-n Print line numbers.
-o Print file names.

Proposition-6: sort command


Ordering a file - The sort command:
Many times you want to arrange contents of a file in specific order. Whether it is comparing files in
alphabetic order or setting up database in numeric order.
The sort command is used to arrange the records in a particular order. By default, the sort command
sorts file assuming the contents are ASCII. It can also be used to sort numerically.
Sort option Description
-k n Sort on n th field, Ex. sort –t “|” –k 2 xyz (sort on 2nd field)
-t char Uses delimiter char to identify fields
-u Removes repeated lines
-n Sort numerically
-r Sort in reverse order
-c Checks if file is sorted
-o filename Places output in file filename
-m list Merges sorted files in list
-k m.n Starts on n th column of m th field
-k m,n Starts sort on m th field and end sort on n th field
-f Case insensitive sort
Example:
$ cat numfile
4
2
27
10
$_

$ sort –n numfile
2
4
10
27
$_
Duplicate lines are removed with the –u (unique) option.

57
Proposition-7: grep command
 Search for a pattern in a file, Search for the given string in a file
 The grep command allows you to search one file or multiple files for lines that contain a
pattern.
 Grep means global regular expression printer.
 Exit status is 0 if matches were found, 1 if no matches were found, and 2 if errors occurred.

Syntax: grep <option> <pattern> <filename(s)>

Example:
$ cat student
Geeta 12123 female thane
Mahesh 24321 male mumbai
Vijay 43231 male mumbai
Ajay 54252 male thane
Sanjay 65421 male thane
Seeta 87652 female mumbai
$_
To search for Sanjay
$ grep sanjay student
Sanjay 65421 male thane
$_

Options of grep command:


Option Description
-c (count) Display number of lines only.
-l (list) To display the file names that matches the pattern.
-h (header) Don’t list filenames.
-n (number) Display the line numbers along with lines.
-s (status) Return exit status only.
-r (reverse) Recursive searching.
-i Ignore case for matching.
-w Checking for full word in a file not for substring.
-v Doesn’t display lines matching expression.
-o Shows only matched string.

Pattern matching operators:


Operator Description
^ (caret) Matching the lines that start with a string
$ (Dollar) Matching the lines that end with a string
* (Asterisk) Refer one or more occurrences of character.
[] {} (Set Parenthesis) Refer set of characters.
+ (Plus) Refer word concatenation.
? (Question) Refer a single character.

58
Example:
“people” The word people anywhere on a line. $ grep “people” temp
“^people” The word people at the start of a line. $ grep “^people” temp
“people$” The word people at the end of a line. $ grep “people$” temp
“^people$” A single line with the word people in it. $ grep “^people$” temp
“a*ll” Asterisk matches zero or more occurrences $ grep “a*ll” temp
of any patterns preceding it in the file.

Proposition-8: more command


The more command is a command line utility for viewing the contents of a file or files once screen at
a time. It supports navigating forwards and backwards through a file and is primarily used for viewing
the contents of a file. It also supports searching for strings or regular expressions and opening the file
at the current point in a text editor.
Syntax: more [“space bar” /f/b/j/k/200G/G] filename
Options Description
[space] Scrolls the display, one screenful of data at a time
j Scrolls forward one line
f Scrolls forward one screen
b Scrolls backwards one screen
k Scrolls backward one line
200 G Goes to line number 200
G Foes to last line of the file

Exercise:
1. Write Commands for:
a. counting number of words in the “data.txt”
b. counting number of lines in “data.txt”
c. counting all characters in “data.txt”
2. Give applications of paste command
3. What are the options of wc command
4. What are different types of filters used in Linux
5. Try the commands and write output with its meaning
a. tr “[a-f]” “[0-5]” <emp
b. tr –s “ “ < emp
c. tr –d “f” < emp

59
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 09
Title of Experiment Use vi editor and perform all editor commands
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of vi editor and perform
commands.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

60
Practical Significance: There are many ways to edit files in Unix. Editing files using the screen
oriented text editor vi is one of the best ways. This editor enables you to edit lines in context with
other lines in the file. An improved version of the vi editor which is called the VIM has also been
made available now, VIM stands for Vi IMproved
A vi session begins by invoking the command vi with or without a filename:
$ vi filename ( $ vi temp)
you are presented with a full empty screen, each line beginning with a ~ (tidle) for text editing, vi uses
24 of the 25 lines that are normally available in a terminal. The last line is reserved for ex commands.
The filename appears in this line with the message “temp” [new file]. The cursor is positioned at top
left hand corner of the screen.
Three modes in which vi works:
Input mode = where any key depressed is entered as text.
Command mode = where key are used as commands to act on text.
Ex mode = where ex commands can be entered in the last line to act on text.

Input mode - Adding and Replacing text


Before you attempt to enter text into the file, you need to change the default command mode to the
input mode. The simplest type of input is insertion of text. To insert text at position press ‘i’. The
character doesn’t show up on the screen, but pressing this key changes the mode from command to
input you will see the words “ INPUT MODE “ at the bottom right corner of the screen. Once you have
pressed I, you can start inserting a few lines of text each line followed by <enter>:
This is the vi editor
It operates in three modes
All features of ex also available
~
~
~
~
~
~

You can use the backspace key to erase any inserted text, one character at a time. You can also effect
a speedier movement by using <control-u> to move back to the beginning of a word. The input mode
is terminated by pressing the <Esc> key, which takes you back to the command mode.

There are other methods of inputting text. To append text to the right of the cursor position use ‘a’
followed by the text you wish to key in. you can append several lines of text in this way. ‘I’ inserts text
at the beginning of a line, while ‘A’ appends text at the end of a line. You can also open a new line by
positioning the cursor at any point in a line and pressing ‘o’. This inserts an empty line below the
current line. ‘O’ also opens a line but above the current line.

Text is replaced with the r, R, s and S keys. To replace one single character by another you
should use ‘r’. To replace more than a single character use ‘R’ followed by the text. Existing text will be
overwritten as the cursor moves forward. The ‘S’ character replaces the single character under the
cursor with existing text; irrespective of its length ‘S’ replaces the entire line.

61
Input mode Commands:
Command Function
i Inserts text to left of cursor
I Inserts text at beginning of line
a Appends text to right of cursor
A Appends text at end of line
o Opens line below
O Opens line above
rch Replaces single character under cursor with char ch
R Replaces text from cursor to right
s Replaces single character under cursor with any number of characters
S Replaces entire line
To switch to the command mode from input mode by pressing the <Esc> key.

Saving Text and Quitting = The last line mode


vi uses the ‘zz’ command to save and quit the editor. To write the buffer into the disk and remain in
the editing mode you should use : w <enter> and to save and quit the editor you should use :x <enter>
which returns you to the shell prompt. The repeat factor = suppose you wish to insert a series of 30
asterisks in one line, so instead of using I and then entering 30 asterisk, a shortcut method will be to
use 30i* followed by either the <enter> or the <esc> key. The results in the entry of a sequence of 30
*’s in the line as shown in below.
Hello
30i* <Esc>
********************* Hello

Deletion: The simplest text deletion is achieved with the ‘x’ command. This command deletes the
character under the cursor. Move the cursor to the character that needs to be deleted and then press
‘x’. A repeat factor applies so 4x deletes the current character as well as three characters from the
right. Entire lines are removed by using the ‘dd’ command move the cursor to any line and then press
‘dd’ once again, you can use a repeat factor. Thus 6dd deletes the current line and following five.

Command Description
x Deletes the character under the cursor location
X Deletes the character before the cursor location
Dw Deletes from the current cursor location to the next word
d^ Deletes from the current cursor position to the beginning of the line
d$ Deletes from the current cursor position to the end of the line
D Deletes from the cursor position to the end of the current line
dd Deletes the line the cursor is on

Cursor movement command:


h, i, k and l these navigation keys, when invoked as such in the command mode, move the cursor by
one position. To move the cursor to the left use ‘h’ or the backspace key. To move cursor to the right
use ‘l’ or the spacebar. The cursor is moved one row up with ‘k’ and one row down with ‘j’.
A repeat factor can be used if necessary. 3h moves the cursor three places to the left while 7k moves
cursor seven places up, you can use the navigation keys described above to move to a specific line, and
then you can move faster along the line by using ^, $, b, e and w keys. To move back to the beginning

62
of a word use ‘b’. While to move forward to the end of a word use ‘e’. To move to start of the next
word use ‘w’. A repeat factor speeds up cursor movement along a line.
Ex. 5b takes the cursor five words back while 3w takes the cursor three words forward. With the ‘^’
taking the cursor to the beginning of the first word in a line use ‘o’ or ‘l’. The $ plays the usual role here
and it takes the cursor to the end of the line.

Cursor Movement Commands:


h or backspace Moves cursor left
j Moves cursor down
k Moves cursor up
l or spacebar Moves cursor right
^ Moves cursor to beginning of first word of line
o or l Moves cursor to beginning of line
$ Moves cursor to end of line
b Moves cursor back to beginning of word
e Moves cursor forward to end of word
w Moves cursor forward to beginning of word

Paging and Scrolling:


To page forward one full screen use <control-f> and to page backward use <control-b> to scroll the
window forward use <control-d> and to scroll backward use <control-u>. The repeat factor can also be
used here thus 5<control-f> scrolls five screens forward while 10<control-u> scrolls ten half screens
backward.
Paging functions:
Command Function
<Control-f> Full page forward
<Control-b> Full page backward
<Control-d> Half page forward
<Control-u> Half page backward
<Control-e> Moves screen up one line
<Control-y> Moves screen down one line
<Control-l> Redraw page screen (no repeat factor)

Moving between lines:


The G command is its “line address” which moves the cursor across lines. A repeat factor takes you to
a specified line. To move to the 40th line use ‘40G’ and to move to the beginning of the file use ‘1G’ the
end of the file is reached by simply using ‘G’.

Searching for a pattern:


Lines can also be located by specifying a pattern as a “context address” such a pattern has to be
preceded by a /, followed by the pattern and then the <enter> key. The pattern can be a simple string
or even a regular expression.

‘?’ pattern <enter> searches backward for the most previous instance of the pattern. Thus the symbol
‘/’ searches in the forward direction while ‘?’ reverse the search. For repeating a search in the direction
in which the precious search was made with ‘/’ or ‘?’ use n and for repeating the search in the reverse
direction use ‘N’.
Search and repeat command:
63
• /pat = Searches forward for pattern pat.
• ?pat = Searches backward for pattern pat.
• n = Repeat search in same direction along which the previous search was made.
• N = Repeats search in a direction opposite to that along with the previous search was made.
• fch = Moves cursor forward to first occurrence of character ch in the ; current line.
• ; = Repeats search in same direction along which the previous search was made with F or t.
• , = Repeats search in a direction opposite to that along which the previous search was made
with F or t.

Joining lines:
Lines can be joined with the J command 4j joins four lines starting with the current line.

Operators:
Text Direction: ‘d’ operator use for delete characters and lines, the ‘d’ operator with the $ to delete
from the cursor position to the end of a line. Use the sequence d$. The command to delete a word
should be equally simple use dw. To delete a complete line double the operator dd.
3dw deletes three words and 5dd deletes five lines, starting with the current line. The deleted text is
placed in a different location with the p and P(put) commands.

Changing Text: Text can be changed with the c operator dw deletes a word while cw changes the
words. To change text from the present cursor position up to the end of a line use c$ or c. To change
entire lines use cc.
Command Description
cc Removes the contents of the line, leaving you in insert mode
cw Changes the word the cursor is on from the cursor to the lowercase w end of the
word
r Replace the character under the cursor. Vi returns to the command mode after
the replacement is entered
R Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting
s Replaces the current character with the character you type. Afterward you are
left in the insert mode
S Deletes the line the cursor is on and replaces it with the new text. Afterword the
new text is entered, vi remains in the insert mode.

Yanking Text: you can copy lines or words from one place and then you can paste them at another
place. The y operator yanks (or copies) text to yank five lines of text, move the cursor to the first of
these and press 5yy or 5y next move the cursor to the new location and press p or P.
Copy and paste commands
Command Description
yy Copies the current line
yw- Copies the current word from the character the lowercase w cursor is on, until
the end of the word
p Puts the copied text after the cursor
P Puts the yanked text before the cursor

64
Ex mode commands for file handling:
Press Esc key and then (:) colon to enter ex-mode commands. A colon is displayed at the left hand
corner of the last line on you screen
Command Function
:w Saves file and remains in editing mode
:w note1 Creates file note1 and writes buffer contents to it
:w >> note1 Appends buffer contents to file note1
:x Saves file and quits editing mode
:wq Saves and quits editing mode
:q Quits editing mode without saving
:q! Quits vi cancelling the changes
:e note1 Stops editing current file and edits file note1
:n Edits next file
:sh Escape to Unix shell

Abbreviation using abbr command:


The abbr command is used to expand short strings to long words
Example
: abbr vp vijay patil
This indicates that when you enter the word vp followed by a key which is neither alphanumeric nor
the underscore character, the word “vijay patil” would be substituted in place of the string.

Exercise:
1. Write command to save the file
2. Write the command to insert text at the end of line
3. Write a command to delete 10 lines at a time
4. Write a command to move cursor 3 word to the right
5. State the three ways to quit the vi-editor
6. What is effect of: set nu, set ic, set nonu, set noai
7. What is difference between yank and delete
8. What are different modes in Vi editor

65
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 10
Title of Experiment Write and execute shell script by using following
control statements features: if statement
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script and control
statements.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

66
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 certain lines of code
otherwise, the program will execute other tasks the programmer specified.

Proposition-1: Steps to write a shell script


1. Create a file in any editor; you must specify the shell you are using in the first line of the file.
#!/bin/bash
Or
#!/bin/sh

2. For example create a file test1 and write a code as follows:


#!/bin/bash
# This script displays the date and who’s logged on
date
who

3. If you try to run the test1 script, following message displays:


$./test1
bash: ./test1: Permission denied
The shell indicated that you don’t have permission to execute the file.

4. Change the file permission to execute the file.


$ ls –l test1
-rw-rw-r-- 1 vtp vtp 66 Jun 16 19:35 test1
$chmod u+x test1 (or chmod 755 test1)

5. Run the script


$./test1
Mon Jun 16 19:36:27 IST 2014
vtp tty7 2014-06-16 19:34
vtp pts/0 2014-06-16 19:34 (:0)
$

Proposition-2: Simple if (Single Decision)


The if-then structure places a condition on several Linux commands The if-then structure begins with
the keyword if and is followed by an expression enclosed in parentheses. The keyword then follows
the expression. You can then specify any number of Linux commands on the following lines. The
keyword endif ends the fi command.
Syntax: Concept diagram:
if [ conditional expression ]
then
statement1
statement2
.
fi

67
Example-1:
#!/bin/bash
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
output:
a is not equal to b

Proposition-3: The if-then-else Statement (if..else) (Double Decision)


If the conditional expression is true, it executes the statement1 and 2. If the conditional expression
returns zero, it jumps to else part, and executes the statement3 and 4. After the execution of if/else
part, execution resume with the consequent statements.
Syntax: Concept diagram:
If [ conditional expression ]
then
statement1
statement2
else
statement3
statement4
fi

Example:
#!/bin/bash
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
Output:
a is not equal to b

Proposition 4: If..elif..else..fi statement (else..if ladder) (Multiple if condition)


You can use this if .. elif.. if , if you want to select one of many blocks of code to execute. It checks
expression 1, if it is true executes statement 1,2. If expression1 is false, it checks expression2, and if all
the expression is false, then it enters into else block and executes the statements in the else block.

68
Syntax: Concept Diagram:
If [ conditional expression1 ]
then
statement1
statement2
.
elif [ conditional expression2 ]
then
statement3
statement4
.
else
statement5
fi
Example:
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
Output:
a is less than b

Proposition 5: Nesting ifs


If statement and else statement could be nested in bash. The keyword “fi” indicates the end of the
inner if statement and all if statement should end with the keyword “fi”.
Syntax: Example:
If [ conditional expression1 ] #!/bin/bash
then count=99
statement1 if [ $count -eq 100 ]
statement2 then
. echo "Count is 100"
else else
if [ conditional expression2 ] if [ $count -gt 100 ]
then then
statement3 echo "Count is greater than 100"
. else
fi echo "Count is less than 100"
fi fi
69
fi

Proposition 6: Relational Operators used with if statement


The most common method for using the test command is to perform a comparison of two numeric
values. The numeric test conditions can be used to evaluate both numbers and variables.
Operation Meaning Example
-eq Checks whether numbers or values of variables are equal [ $a -eq $b ]
-ne Checks if the numbers are unequal [ $a -ne $b ]
-gt Checks if the first number is greater than the second [ $a -gt $b ]
-lt Checks if first number is less than the second [ $a -lt $b ]
-ge Checks if first number is greater than or equal to second [ $a -ge $b ]
-le Checks if first number is less than or equal to second [ $a -le $b ]

Programs:
1. Write script for finding greatest number among given three number
#!/bin/bash
echo "enter first number"
read first
echo "enter second number"
read sec
echo "enter third number"
read third
if [ $first -gt $sec ] ; then
if [ $first -gt $third ] ; then
echo -e " $first is greatest number "
else
echo -e " $third is greatest number "
fi
else
if [ $sec -gt $third ] ; then
echo -e " $sec is greatest number "
else
echo -e " $third is greatest number "
fi
fi

2. Write script to check whether entered year is leap year or not


#!/bin/bash
echo "Enter Year:"
read y
year=$y
y=$(( $y % 4 ))
if [ $y -eq 0 ]
then
echo "$year is Leap Year!"
else
echo "$year is not a Leap Year!"
fi

70
3. Write a shell program to check whether the given number is less than 10 or not?
$cat check
#!/bin/bash
#check number
echo “enter any no. from 1 to 10”
read number
if [ $number –lt 10 ]
then echo ”small number”
else
echo “large number”
fi
output:
$./check
enter any no. from 1 to 10
5
small number
$./check
enter any no. from 1 to 10
15
large number

4. Write a shell program to checks the category of user on the basis of age.
$ cat age
#!/bin/bash
echo “Enter your age”
read age
if [$age –lt 13]
then echo “A Child”
elif [$age –le 19]
then echo “Teenage”
elif [$age –lt 30]
then echo”Youth”
elif [$age –lt 50]
then echo “Middle Age”
else echo “Old Age”
fi
$_
output:
Enter your age
15
Teenage

5. Write Shell Script to find Number is Even or Odd


$cat evenodd
#!/bin/bash
echo "Enter a Number:"
read n
rem=$(( $n % 2 ))
if [ $rem -eq 0 ]
then
echo "Number is even"

71
else
echo "Number is odd"
fi
output:
Enter a number
4
Number is even
Enter a number
5
Number is odd

72
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 11
Title of Experiment Write and execute shell script by using following
control statements features: for, exit, break, continue
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script and control
statements.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

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

Proposition-1: for statement


The bash shell provides the for command to allow you to create a loop that iterates through a series
of values. Each iteration performs a defined set of commands using one of the values in the series.
Syntax:
for var in list or for variable in 1 2 3 4 5 .. N
do do
commands command1
done command2
commandN
done
Example:
$ cat test1
#!/bin/bash
for name in Smith John William
do
echo "$name is my friend"
done
$ ./test1
Smith is my friend
John is my friend
William is my friend

Proposition-2: Three expression bash for loop syntax


This type of for loop can also be used similar to the C programming language. It is having by a three
parameter loop control expression; consisting of an initializer (exp-1), a loop test or condition (exp-
2), and a counting expression (Exp-3)
Example:
#!/bin/bash
for ((i=0;i<=5;i++))
do
echo $i
done

Output:
1
2
3
4
5

Proposition-3: break statement


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.
Syntax: break
The break command can also be used to exit from a nested loop using this format:
Syntax: break n

74
Here n specifies the nth enclosing loop to the exit from.
Example:
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
output:
0
1
2
3
4
5

Proposition-4: continue statement


The continue statement is similar to the break command, except that it causes the current iteration
of the loop to exit, rather than the entire loop.
This statement is useful when an error has occurred but you want to try to execute the next iteration
of the loop.
Syntax: continue
Like with the break statement, an integer argument can be given to the continue command to skip
commands from nested loops.
Syntax: continue n
Here n specifies the nth enclosing loop to continue from.
Example:
#!/bin/sh
a=0
while [ $a -lt 5 ]
do
if [ $a -eq 3 ]
continue
else
echo $i
a=`expr $a + 1`
done
output:
0
1
2
4
5

75
Proposition-5: exit statement
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]

Proposition-6: while statement


The while statement is used to execute a list of commands repeatedly. The while command allows you
to define a command to test, then loop through a set of commands for as long as the defined test
command returns a zero exit status. It tests the test command at the start of each iteration. When the
test command returns a non-zero exit status, the while command stops executing the set of
commands.
Syntax: Concept Diagram:
while [ condition ]
do
command1
command2
..
....
commandN
done

Example:
$ cat test
#!/bin/bash
# while command test
var1=0
while [ $var1 -le 10 ]
do
echo $var1
var1=$[ $var1 + 1 ]
done
$ ./test
1
2
3
4
5
6
7
8
9
10
$

76
Proposition-7: until statement
The until loop is very similar to the while loop, except that the loop executes until the test-command
executes successfully. As long as this command fails, the loop continues.
Syntax:
until test commands
do
other commands
done

Example:
$ cat test10
#!/bin/bash
# until command test
var1=0
until [ $var1 -ge 10 ]
do
echo $var1
var1=$[ $var1 + 1 ]
done
$ ./test10
1
2
3
4
5
6
7
8
9
10
$

Proposition-8: case statement


 The case statement allows you to easily check pattern (conditions) and then process a
command-line if that condition evaluates to true.
 The case command compares the variable specified against the different patterns. If the
variable matches the pattern, the shell executes the commands specified for the pattern.
 You can list more than one pattern on a line, using the bar operator to separate each pattern.
 *) acts as default and it is executed if no match is found.
 You must include ;; at the end of each commandN. The shell executes all the statements up to
the two semicolons that are next to each other.
 The esac is always required to indicate end of case statement.
Syntax:
case variable in
pattern1)
commands;;
pattern2)
commands;;
pattern3)
commands;;

77
*) default
commands;;
esac
Concept Diagram:

Example-1:
#!/bin/sh
FRUIT="orange"
case "$FRUIT" in
"apple") echo "It’s an Apple."
;;
"banana") echo "It’s a banana."
;;
"orange") echo "It’s an Orange."
;;
esac
output:
It’s an Orange.

Example-2:
echo “enter no”
read no
case “no” in
0) echo “Zero”;;
1) echo “One”;;
2) echo “Two”;;
|
9) echo “Nine”;;
*) echo “Invalid Argument”;;
Esac

78
Programs
1. Write a shell program to copy the content of one file into another file
$ cat test
#!/bin/bash
echo “enter source and target filename”
read source target
if cp $source $target
then
echo “file copied successfully”
else
echo “file copy is failed”
fi

2. Write a shell script to display first 10 natural numbers.


i=1
while [ $i -le 10 ]
do
echo $i
i=`expr $i + 1`
done
output:
1
2
3
4
5
6
7
8
9
10

3. Write a shell script to find out the factorial of the given number.
i=1
f=1
echo " Enter the number"
read n
while [ $i -le $n ]
do
f=`expr $f \* $i`
i=`expr $i + 1`
done
echo FACTORIAL = $f
output:
Enter the number
5
FACTORIAL=120

79
4. Write a shell script to find out whether the given number is prime number or not.
echo Enter the number
read n
i=1
c=0
while [ $n -ge $i ]
do
if [ `expr $n % $i` -eq 0 ]
then
c=`expr $c + 1`
fi
i=`expr $i + 1`
done
if [ $c -eq 2 ]
then
echo Prime Number
else
echo Not Prime number
fi
output
Enter the number
5
Prime number
Enter the number
4
Not Prime number

5. Write a shell script to find out sum of the digits of the given number.
sum=0
echo " Enter the number"
read n
while [ $n -gt 0 ]
do
temp=`expr $n % 10`
sum=`expr $sum + $temp`
n=`expr $n / 10`
done
echo $sum
output
Enter the number
234
9

6. Write a menu program to display following:


$ cat menu
#!/bin/bash
cat << END
echo “MENU”
echo “1. List of files and directories”
echo “2.Processes of user”
echo “3.Today’s date”
echo “4.Users of System”

80
echo “5.Free disk space”
echo “6.Quit to Unix”
echo “Enter you choice”
read ch
case $ch in
1) ls –l;;
2) ps –f;;
3) date ;;
4) who;;
5) df;;
6) exit;;
esac

7. Write script to print odd numbers.


#!/bin/bash
i=1
while [ $i -le 10 ]
do
echo "$i"
i=`expr $i+2`
done
output
1
3
5
7
9

8. Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.
#cat rev
#!/bin/bash
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find reverse of given number"
echo " For eg. $0 123, I will print 321"
exit 1
fi
n=$1
rev=0
sd=0

while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd`
n=`expr $n / 10`
done
echo "Reverse number is $rev"
output
#./rev 123
Reverse number is321

81
9. Write a shell script to find out whether the given string is Palindrome or not using command line
argument
#cat palin
#!/bin/bash
s=`echo $1 | wc -c`
while [ $s -gt 0 ]
do
temp=`echo $1 | cut -c $s`
s=`expr $s - 1`
temp1="$temp1$temp"
done
echo "Reverse string is $temp1"
if [ $1 = $temp1 ]
then
echo “The given string is palindrome”
else
echo “ Not palindrome”
fi
output
#./palin madam
Reverse string is madam
The given string is palindrome

10. Shell Script to print the Fibonacci Numbers


echo Enter the number
read n
i=1
f=0
s=1
next=`expr $f + $s`
echo $f
echo $s
echo $next
while [ $i -le `expr $n - 3` ]
do
f=$s
s=$next
next=`expr $f + $s`
echo $next
i=`expr $i + 1`
done
output
Enter the number
10
0
1
1
2
3
5
8

82
11. Write a shell script to generate a multiplication table
echo Multiplication Table:
echo Which table do you want ? (Give Number):
read num
iter=1
while [ $num –le 5 -a $iter -le 10 ]
do
res=`expr $num \* $iter`
echo $num “*” $iter “=” $res
iter=`expr $iter + 1`
done
output:
Multiplication Table:
Which table do you want ? (Give Number):
3
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

12. Write a program to print all prime numbers from 1 to 100.


#!/bin/bash
echo “Enter no”
read num
for ((i=1;i<num;i++))
do
flag=0
for((j=2;j<I;j++))
do

if[`expr $i % $j` -eq 0 ]


then
flag=1
fi
done
if[$flag –eq 0]
then echo $i
fi
done
output
Enter no
20
1
2
3
5
7
83
11
13
17

13. Write shell script using for loop to print the following patterns on screen
Pattern-1
for (( i=1; i<=5; i++ ))
do
for (( j=1; j<=i; j++ ))
do
echo -n "$i"
done
echo ""
done
output:
1
22
333
4444
55555

Exercise:
 State the difference between iteration and recursion
 Write a shell script to find largest number from three numbers.
 Write script to print Even numbers.
 Write a shell script to perform arithmetic operations using case statement.
 Execute shell script by considering example like printing table of given number by for loop
 Write a shell script to display tables of 2 to 10 numbers (like 2*1=2)
 Write shell script to print following output

1 * * ****
12 ** * ***
123 *** * **
1234 **** * *
12345 *****
*

84
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 12
Title of Experiment Write shell script to find out whether given file exists
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script for perform
permission on file.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

85
Practical Significance: In Unix 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).
The test command allows you to test the status of files and directories on the Linux file system. These
conditions give you the ability to check files in your file system within your shell scripts, and they are
often used in scripts that access files.

Proposition-1: Types of files


In Unix Operating System files are categories into three parts:
1. Ordinary file: It consists of stream of data resident on some permanent magnetic media you can put
anything you want into this type of file. This includes all data, source programs, object and executable
code, all UNIX programs, commands like pwd, ls etc are treated as ordinary files. This file is also
referred to as an ordinary file or a regular file.
2. Directory file: A directory consists of a programs and sub-directories. A directory contains no data,
but keeps on account of all the files and sub directories that it contains. A directory file contains two
fields the name of a file and a pointer to a separate disk area, which contains the files, attributes.
3. Device file: These are files that represent physical devices. This definition of a file includes printers,
tapes, floppy disks, hard disks and terminals. The device file is special in the sense that any output
directed to it will be reflected onto the respective input/output device associated with the filename.

Proposition-2: file test operators


Comparison Description
-b file Check if file exists and is block special file.
-c file Check if file exists and is character special file.
-d file Check if file exists and is a directory.
-e file Checks if file exists.
-f file Checks if file exists and is a file.
-g file Check if file exists and is set-group-ID.
-h file Check if file exists and is a symbolic link.(same as –L)
-k file Check if file exists and has its sticky bit set.
-L file Check if file exists and is a symbolic link.(same as –h)
-O file Checks if file exists and is owned by the current user.
-G file Checks if file exists and the default group is the same as the current user.
file1 -nt file2 Checks if file1 is newer than file2.
file1 -ot file2 Checks if file1 is older than file2.

Programs
1. Write a shell script to check whether a given argument is a directory or not
$ cat check
#!/bin/bash
# Script to check for directory files
read f1
if [ –d $f1]
then echo “ $f1 is a directory”
ls
else mkdir $f1
fi

86
2. Write a shell script to check whether a given argument is a file or not
$ cat check
#!/bin/bash
#file test
echo “enter file name”
read file
if [ -f $file ]
then echo “file is exit”
else echo “$file is not a file”
fi

Exercise:
 What are file test options with its meaning?
 Write a shell script which accept input as a file or directory and displays message whether it is
file or directory.
 Write a shell script which displays list of all directories in your home directory.

87
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 13
Title of Experiment Write shell script to find out whether file has read,
write and execute permissions
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script for perform
permission on file.

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

88
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: owner 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.

Proposition-1: Test commands for check permission

Comparison Description
-r file Checks if file exists and is readable.
-s file Checks if file exists and is not empty.
-w file Checks if file exists and is writable.
-x file Checks if file exists and is executable.

Exercise:
 What are permissions of a file?
 How to assign permission to a file?
 How to check permissions of all files and directories?
 What are the test commands to check the permission of a file?
 Write a shell script which displays the list of all executable files in the current working
directory.
 Write a shell script which displays a list of all the files in the current working directory which
user has read, write and execute permission.
 Write a shell script which accepts a filename and assigns it all the permissions.

89
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 14
Title of Experiment Write a program to calculate total waiting and
turnaround time of a processes with first come first
serve CPU scheduling algorithms.
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and implement the FCFS Scheduling
algorithms

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

90
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 CPU scheduling. The
Operating system uses various scheduling algorithm to schedule the processes. First Come First Serve
(FCFS) scheduling algorithm simply schedules the jobs according to their arrival time.

Proposition-1: First Come First Serve (FCFS) scheduling algorithm


It is the simplest type of algorithm in which the process that requests the CPU first is allocated the CPU
first. FCFS policy is easily managed with a FIFO queue. When process enters the ready queue its process
control block is linked onto tail of the queue. When CPU is free it is allocated to the process at the head
of queue. The running process is then removed from the queue. The average time (waiting time) under
FCFS policy is quite long. Consider the following set of processes that arrive at time 0, with the length
of CPU burst time given in milliseconds. The average waiting time under FCFS policy is generally not
minimal and may vary greatly. The FCFS scheduling algorithm is non-pre-emptive. Once the CPU has
been allocated to a process, that process keeps the CPU until it releases the CPU, either terminating
or by requesting I/O.
Case-1: Consider the four jobs are scheduled for execution (all jobs arrived at same time). Find the
average waiting time and turnaround time.
Process CPU Burst Time
P1 8
P2 4
P3 9
P4 5
Solution:
Gantt chart

Waiting Time Turnaround Time


Waiting time of Process P1= 0 TAT of process P1= 8
Waiting time of Process P2= 8 TAT of process P2= 12
Waiting time of Process P3= 12 TAT of process P3= 21
Waiting time of Process P4= 21 TAT of process P4= 26
Average Waiting Time=(0+8+12+21)/4 = 41/4 Average TAT=(8+12+21+26)/4 = 67/4 =16.75
=10.25

Questions:
1. Compare SJF, priority and RR
Parameter FCFS algorithm SJF algorithm Priority Algorithm RR Algorithm
Preemption This scheduling This scheduling This scheduling This scheduling
algorithm is non algorithm is algorithm is also algorithm is also
preemptive. preemptive. preemptive. preemptive.
Complexity This is simplest This algorithm is This algorithm is In this scheduling
scheduling difficult to also difficult to algorithm
algorithm. understand and understand. performance
code. heavily depends

91
upon the size of
time quantum.
Allocation In this scheduling In this scheduling This scheduling In this scheduling
algorithm it algorithm CPU is algorithm is based algorithm the
allocates the CPU allocated to the on priority the preemption take
in the order in process with least higher priority job place after a fixed
which the CPU burst time. can run first. interval of time.
processes arrives.
Application This scheduling This scheduling This scheduling This scheduling
algorithm is good algorithm is also algorithm is also algorithm is good
for non interactive good for non good for non for interactive
system. interactive interactive system.
system. system.
Waiting Time In this scheduling In this scheduling In this scheduling
In this scheduling
algorithm the algorithm the algorithm the
algorithm the
Average waiting Average waiting Average waiting Average waiting
time is large. time is small as time is small astime is large as
compare to FCFS compare to FCFS compare to all the
scheduling scheduling three scheduling
algorithm. algorithm. algorithm.
Usability This scheduling In this scheduling This scheduling
In this scheduling
algorithm is never algorithm the algorithm is thealgorithm if the
recommended problem is to sometime quantum size is
whenever know the length of becomes the
large then this
performance is a time for which the biggest cause ofalgorithm become
major issue. CPU is needed by starvation. same as FCFS
the process. algorithm and its
performance
degrade.
Type of This scheduling This scheduling This scheduling This scheduling
System algorithm is algorithm is also algorithm is based algorithm is suitable
suitable for Batch suitable for Batch upon priority. for time sharing
system. system. system.

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


 Pre-emptive Scheduling: If a higher priority process is entering the system, the currently
running process is stopped and the CPU transfers the control to the higher priority process. The
currently running process may be interrupted and moved to the ready state by the operating
system. Window-95 introduces preemptive scheduling and all subsequent versions of Windows
operating systems have used preemptive scheduling. The Mac OS X operating system for the
Macintosh also uses preemptive scheduling.
 Non Pre-emptive Scheduling: once the CPU has been allocated to a process, the process keeps
the CPU until it releases the CPU either by terminating or by switching to the waiting state. This
scheduling method was used by Microsoft Windows 3. In this case, once a process is in the
running state, it continues to execute until it terminates or blocks itself to wait for I/O or by
requesting some operating system services. i.e. if a higher priority process enters the system,
the running process cannot be forced to release the control.

92
3. Give the reason of problem arises in FCFS
The average waiting time under FCFS policy is generally not minimal and may vary greatly. The FCFS
scheduling algorithm is non-pre-emptive. Once the CPU has been allocated to a process, that process
keeps the CPU until it releases the CPU, either terminating or by requesting I/O.
Disadvantages of FCFS Scheduling:
 Average waiting time is very large
 FCFS is not an attractive alternative on its own for a single processor system
 Another difficulty with FCFS tends to favor processor bound. Processes over I/O bound
processes and may result in inefficient use of both the processor and the I/O devices.

4. Write a formula for turnaround time


Turnaround time (TAT) is the time interval from the time of submission of a process to the time of the
completion of the process. It can also be considered as the sum of the time periods spent waiting to
get into memory or ready queue, execution on CPU and executing input/output.
Turn Around Time = Completion Time – Arrival Time

5. Write a formula for Average waiting time


The CPU scheduling algorithm does not affect the amount of time during which a process executes of
does I/O, if affects only the amount of time that a process spends waiting in the ready queue. Waiting
time is the sum of the periods spent waiting in the ready queue. Time Difference between turnaround
time and burst time.
Waiting Time = Turn Around Time – Burst Time

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. Turnaround time for each process
2. Waiting time for each process
3. Average turnaround time
4. Average waiting time
Process Burst Time
P1 21
P2 6
P3 3
P4 2

‘C’ Code:
#include<stdio.h>

int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);

printf("\nEnter Process Burst Time\n");


for(i=0;i<n;i++)
{
93
printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
}

wt[0]=0; //waiting time for first process is 0

//calculating waiting time


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

//calculating turnaround 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 Waiting Time:%d",avwt);
printf("\nAverage Turnaround Time:%d",avtat);

return 0;
}

Output:
Enter total number of processes (maximum 20):4
Enter Process Burst Time
P[1]:21
P[2]:6
P[3]:3
P[4]:2

Process Burst Time Waiting Time Turnaround Time


P[1] 21 0 21
P[2] 6 21 27
P[3] 3 27 30
P[4] 2 30 32
Average Waiting Time:19
Average Turnaround Time:27

94
Exercise:
1. Solve the problem using FCFS algorithm and preemptive SJF. Find average waiting time and
turnaround time using Gantt chart
Process Arrival Time Burst Time
P1 0 10
P2 1 4
P3 2 14
P4 3 8

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

95
Program: Computer Engineering

Course : Operating System Course Code: 22516


Semester: V Class:
Laboratory No: Name of Subject Teacher:
Name of Student: Roll ID:

Experiment No. 15
Title of Experiment Write a C program to implement FIFO page
replacement algorithm
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and implement the FIFO page
replacement algorithms

Dated Signature of Teacher


Marks Obtained
Process Related Product Related Total
(15) (35) (50)

96
Practical Significance: When there is a page fault, the referenced page must be loaded. If there is no
available frame in memory, then on 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 new page comes in.

Proposition-1 FIFO (First-In First-Out) Page Replacement Algorithm:


The simplest page replacement algorithm is a FIFO. A FIFO replacement algorithm associates with each
page the time when that page was brought into memory. When a page must be replaced, the oldest
page is chosen. FIFO queue is created to hold all pages in memory. We replace the page at the head of
the queue. When a page is brought into memory, we insert it at the tail of the queue. The FIFO page
replacement algorithm is easy to understand and program. It performance is not always good.
For example consider the following reference string: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0
Our three frames are initially empty. The first three references (7, 0, 1) cause page faults and are
brought into these empty frames. The next reference (2) replaces page 7, because page 7 was brought
in first. Since 0 is the next reference and 0 is already in memory, we have no fault for this reference.
The first reference to 3 results in page 0 being replaces, since it was the first of the three pages in
memory (0, 1, and 2) to be brought in. Because of this replacement, the next reference 0 will fault.
Page 1 is then replaced by 0. This process continues. There are 15 faults altogether.

7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1

Problem of FIFO Algorithm:


Consider the following reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5

Fig. Page fault for using Three frames

Fig. Page fault for using Four frames


The number of faults for four frames (10) is greater than the number of faults for three frames (9). This
most unexpected result is known as Belady’s anomaly. For some page replacement algorithms, the
97
page fault rate may increase as the number of allocated frames increases. We would expect that giving
more memory to a process would improve its performance.
Advantages of FIFO Page Replacement Algorithm
 It is simple to implement.
 It is easiest algorithm
 Easy to understand and execute.

Disadvantages of FIFO Page Replacement Algorithm


 It is not very effective
 A page that has been memory for a long time could equally likely be frequently used or
unused, but FIFO treats them the same way.
 System needs to track of each frame.
 Its performance is not always good.
 Its suffers from Belady’s anomaly.
 Bad replacement choice increases the page fault rate and slow process execution.

Questions:
1. What is page hit?
When we want to load the page on the memory, and the page is already available on memory, then
it is called page hit.

2. What is page fault


When we want to load the page on the memory, and the page is not already on memory, then it is
called page fault. The page fault is also called page miss.

3. Compare FIFO and LRU


FIFO LRU
FIFO stands for First in First Out LRU - stand for 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

Exercise:
1. Consider the reference string 9,7,6,1,7,6,1,2,7,2 the number of frames in memory is 3. Find out the
number of page faults and page hit respective to
 FIFO page replacement algorithm
 Optimal page replacement algorithm
 LRU page replacement algorithm

Program for FIFO Page Replacement Algorithm


Algorithm
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Forma queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted

98
9. Display the values
10. Stop the process

‘C’ Code:
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,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]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
}

Output:
ENTER THE NUMBER OF PAGES
20
ENTER THE PAGE NUMBER
12321521625631361243
ENTER THE NUMBER OF FRAMES
3

ENTER THE NUMBER OF FRAMES :3


ref string page frames
1 1 -1 -1
2 1 2 -1
3 1 2 3
2
99
1
5 5 2 3
2
1 5 1 3
6 5 1 6
2 2 1 6
5 2 5 6
6
3 2 5 3
1 1 5 3
3
6 1 6 3
1
2 1 6 2
4 4 6 2
3 4 3 2
Page Fault Is 14

100

DRM Software Review

Вам также может понравиться