Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

IT7411

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

MADRAS INSTITUTE OF TECHNOLOGY

ANNA UNIVERSITY
DEPARTMENT OF INFORMATION TECHNOLOGY

IT7411 – OPERATING SYSTEMS LABORATORY


LAB MANUAL
REGULATION - 2015

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 1|Page


Vision of the Department

To educate students with conceptual knowledge and technical skills in the field of
Information Technology with moral and ethical values to achieve excellence in an academic,
industry and research centric environment.

Mission of the Department

1. To inculcate in students a firm foundation in theory and practice of IT skills coupled with
the thought process for disruptive innovation and research methodologies, to keep pace with
emerging technologies.
2. To provide a conducive environment for all academic, administrative, and interdisciplinary
research activities using state-of-the-art technologies.
3. To stimulate the growth of graduates and doctorates, who will enter the workforce
as productive IT engineers, researchers, and entrepreneurs with necessary soft skills, and
continue higher professional education with competence in the global market.
4. To enable seamless collaboration with the IT industry and Government for consultancy and
sponsored research.
5. To cater to cross-cultural, multinational, and demographic diversity of students.
6. To educate the students on the social, ethical, and moral values needed to make significant
contributions to society.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 2|Page


Program Educational Objectives (PEO)

After completion of the B.Tech. (IT) course, students will be able to:

PEO1: Demonstrate core competence in basic engineering and mathematics to design,


formulate, analyse, and solve hardware/ software engineering problems.
PEO2: Have insight in fundamental areas of Information Technology and related engineering
with an inclination towards self-learning to address real-world problems using digital and
cognitive technologies.
PEO3: Collaborate with industry, academic and research institutions for product and research
related development.
PEO4: Imbibe high professionalism, effective communication skills and team spirit to work
on multidisciplinary projects, in diverse professional environments.
PEO5: Practice IT solutions following technical standards with ethical values.

Program Specific Outcomes(PSO)

PSO1: To apply programming principles and practices for the design of software solutions in
an internet-enabled world of business and social activities.

PSO2: To identify the resources to build and manage the IT infrastructure using the current
technologies in order to solve real world problems with an understanding of the trade-offs
involved in the design choices.
PSO3: To plan, design and execute projects for the development of intelligent systems with a
focus on the future

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 3|Page


IT7411 OPERATING SYSTEMS LABORATORY LTPC
0 0 4 2
OBJECTIVES:
 To learn about the basic commands of operating systems
 To learn various process management schemes in operating systems
 To practice with the important memory management mechanisms in operating system
 To implement the file handling techniques in operating systems

Exercises
1. Basic unix commands such as ls, cd, mkdir, rmdir, cp, rm, mv, more, lpr, man, grep, sed,
etc.,
2. Shell script
3. Process control System calls - demonstration of fork, execute and wait
4. Thread management
5. Thread synchronization
6. Deadlock avoidance using semaphores
7. Interprocess communication using pipes
8. Interprocess communication using FIFOs
9. Interprocess communication using signals
10. Implementation of CPU scheduling policy in Linux
11. Implement a memory management policy in Linux
12. Implement a file system in Linux
13. Linux kernel configuration
TOTAL: 60 PERIODS
OUTCOMES:
On Completion of the course, the students should be able to:
 Learn the concepts to identify, create and maintain the basic command in operating
systems
 Express strengths and limitations of various managements schemes in operating
systems
 Explain the core issues of operating systems
 Implement algorithms of operating systems.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 4|Page


Mapping of Course Outcomes (COs) with Program Outcomes (POs)

Program Outcomes(POs)
CO PSO1 PSO2 PSO3
1 2 3 4 5 6 7 8 9 10 11 12
Learn the 1 2 3 1 1 1 0 0 0 0 0 2 2 2 2
concepts to
identify, create
and use the
basic command
in operating
systems

Familiarize 1 2 3 2 1 0 0 0 0 0 0 1 2 2 2
strengths and
limitations of
various
managements
schemes in
operating
systems

Implement core 1 2 2 3 3 1 0 0 0 0 1 1 2 2 2
concepts/ issues
of operating
systems

Implement 1 2 2 3 3 2 2 0 0 0 1 1 2 2 2
algorithms of
operating
systems

Exploration of 1 2 2 3 3 2 2 0 0 0 1 1 2 2 2
memory
management
methodologies

Exploration of 1 2 3 3 3 3 3 1 0 0 1 1 2 2 2
interprocess
communication
strategies

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 5|Page


GRADING RUBRIC FOR LABORATORY COURSES

Good Marks Average Marks Satisfactory Marks


(81%-100%) (50%-80%) (< 50%)
Lack of detailed procedure
as well as coding samples
Continuous Presence of detailed
Clarity of the procedure with incorrect
procedure, coding samples
Assessment and coding samples are implementation.
with proper
(Covers Preparedness, average with partial
implementation.
Basic implementation, implementation. Able to Unable to adapt the changes
Ability to adapt additional understand the changes in coding.
Able to adapt the changes in
features and coding but unable to implement it.
the code quickly.
standards) (Max Fairly presented code with Coding standards are not
Marks:25) medium standards. followed. Code is messy.
Proper Coding Style.

Laboratory Test (Covers Lack of understanding and


Problem understood clearly Problem understood but
Understanding of problem, problem-solving ability is
and solved. problem solving is not full-
Basic Problem Solving and poor.
fledged.
Ability to code, test, run Implementation not
Complete implementation Completion of three fourths
and debug within the completed/ Partial
with proper test data within of the implementation with
stipulated time) (Max implementation within the
the stipulated time. proper test data.
Marks:25) stipulated time.

Course Oriented Selection of fair problem


Laboratory Project Selection of good real time Selection of good real time with incomplete
(Covers Problem problem with Complete problem with partially implementation. Lack of
Selection, implementation with in- complete implementation proper knowledge and
Demonstration of the depth understanding on the and good knowledge on the understanding on the
Project, Wide coverage of concepts implemented. concepts implemented. concepts implemented.
concepts in the target Wide coverage of concepts Moderate coverage of
language) (Max in the target language. concepts. Limited coverage of
Marks:25) concepts.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 6|Page


S.NO NAME OF THE EXPERIMENT
1. INTRODUCTION TO OPERATING SYSTEMS

2. LINUX COMMANDS FILE SYSTEM

3. SHELL PROGRAMMING BASICS

4. SHELL SCRIPTING – OPERATORS, FUNCTIONS

5. SHELL ARRAYS

6. PROCESS SYSTEM CALLS – FORK, EXIT, WAIT

7. INTERPROCESS COMMUNICATION USING PIPE

8. INTERPROCESS COMMUNICATION USING NAMED


PIPE
9. MULTITHREADING USING PYTHON

10. FILE ALLOCATION STRATEGIES

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 7|Page


EX.NO: 1 INTRODUCTION TO OPERATING SYSTEMS

AIM
To the study the functions of an operating system.
1.1 OVERVIEW
An Operating System (OS)(as shown in Fig 1) is an interface between a
computer user and computer hardware. An operating system is a software
which performs all the basic tasks like file management, memory management,
process management, handling input and output, and controlling peripheral
devices such as disk drives and printers.
Some popular Operating Systems include Linux Operating System,
Windows Operating System, VMS, OS/400, AIX, z/OS, etc. Following are some
of important functions of an operating System:
 Memory Management
 Processor Management
 Device Management
 File Management
 Security
 Control over system performance
 Job accounting
 Error detecting aids
 Coordination between other software and end users.

Figure 1. Operating System

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 8|Page


1.2 LINUX OPERATING SYSTEM
Linux is a free and open source operating system and it is a clone version
of UNIX operating system. It is open source as its source code is freely
available. It is free to use. Linux was designed considering UNIX compatibility.
Its functionality list is quite similar to that of UNIX.

1.2.1 LINUX ARCHITECTURE

Figure 2. Linux OS Architecture

The architecture of a linux system consists of the following layers −


Hardware layer
Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
Kernel
It is the core component of Operating System, interacts directly with
hardware, provides low level services to upper layer components.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 9|Page


Shell
An interface to kernel, hiding complexity of kernel's functions from users.
The shell takes commands from the user and executes kernel's functions.
Utilities
Utility programs that provide the user most of the functionalities of an
operating systems.
1.2.2 COMPONENTS OF A LINUX OPERATING SYSTEM
Linux operating system has primarily three components:
Kernel
Kernel is the core part of linux. It is responsible for all major activities of
this operating system. It consists of various modules and it interacts directly with
the underlying hardware. Kernel provides the required abstraction to hide low
level hardware details to system or application programs.
System Library
System libraries are special functions or programs using which
application programs or system utilities accesses Kernel's features. These
libraries implement most of the functionalities of the operating system and do
not requires kernel module's code access rights.
System Utility
System Utility programs are responsible to do specialized, individual level
tasks.

Figure 3. Linux Operating System

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 10|Page


1.2.3 KERNEL MODE VS USER MODE
Kernel component code executes in a special privileged mode called
kernel mode with full access to all resources of the computer. This code
represents a single process, executes in single address space and do not
require any context switch and hence is very efficient and fast. Kernel runs each
processes and provides system services to processes, provides protected
access to hardware to processes.
Support code which is not required to run in kernel mode is in System
Library. User programs and other system programs works in User Mode which
has no access to system hardware and kernel code. User programs/ utilities
use System libraries to access Kernel functions to get system's low level tasks.
1.2.4 BASIC FEATURES
Following are some of the important features of linux operating system
 Portable

Portability means software can work on different types of hardware in


same way. Linux kernel and application programs supports their installation on
any kind of hardware platform.
 Open Source

Linux source code is freely available and it is community based


development project. Multiple teams work in collaboration to enhance the
capability of Linux operating system and it is continuously evolving.
 Multi User

Linux is a multiuser system means multiple users can access system


resources like memory/ ram/ application programs at same time.
 Multiprogramming

Linux is a multiprogramming system means multiple applications can run


at same time.
 Hierarchical File System

Linux provides a standard file structure in which system files/ user files
are arranged.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 11|Page


 Shell
Linux provides a special interpreter program which can be used to execute
commands of the operating system. It can be used to do various types of
operations, call application programs. etc.

 Security

Linux provides user security using authentication features like password


protection/ controlled access to specific files/ encryption of data.
1.3 COMPARISONS BETWEEN LINUX OS WITH DIFFERENT OS
1.3.1 LINUX VS WINDOWS
Linux OS
Linux could be a free and open supply OS supported operating system
standards. It provides programming interface still as programme compatible
with operating system primarily based systems and provides giant selection
applications. A UNIX operating system additionally contains several severally
developed parts, leading to UNIX operating system that is totally compatible
and free from proprietary.
Windows OS
Windows may be a commissioned OS within which ASCII text file is
inaccessible. it’s designed for the people with the angle of getting no
programming information and for business and alternative industrial users. it‟s
terribly straightforward and simple to use.
The distinction between Linux and Windows package is that Linux is
completely freed from price whereas windows is marketable package and is
expensive. Associate operating system could be a program meant to regulate
the pc or computer hardware.
Linux is an open supply package wherever users will access the ASCII
text file and might improve the code victimisation the system. On the opposite
hand, in windows, users can’t access ASCII text file, and it’s an authorized OS.
Let’s sees that the difference between Linux and windows:

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 12|Page


S.N LINUX WINDOWS

1. It is an open source operating It is a commercial operating


system system (closed source)
2. In linux, monolithic kernel is used In windows, micro kernel is used.

3. In the comparison of file system, Windows are slower compared to


linux runs faster even with older Linux
hardware
4. Linux files are ordered in a tree In windows, files are stored in
structure starting with the root folders on different data drives like
directory. C: D: E:
5. It is customizable It is not possible to customize the
windows OS
6. It supports multiple desktop It supports only preinstalled
environments desktop environment
7. It is more secure than windows Vulnerable to viruses and malware
attacks.
8. Booting takes either primary or In windows, booting supports only
logical partition in linux primary partition

1.3.2 LINUX VS MAC


Linux
Linux is a group of open source Unix-like operating systems which was
developed by Linus Torvalds. It is a packaged of Linux distribution. Some of the
mostly used Linux distribution are Debian, Fedora and Ubuntu. It was basically
written in C language and assembly language. Kernel used in Linux is
Monolithic kernel. The target systems of Linux distributions are cloud
computing, embedded systems, mobile devices, personal computers, servers,
mainframe computers and supercomputers. The first version of Linux was
launched in 1991.
MAC
Mac OS is a series of proprietary graphical operating systems which is
provided by Apple Incorporation. It was earlier known as Mac OS X and later
OS X. It is specifically designed for Apple mac computers. It is based on Unix
operating system. It was developed using C, C++, Objective-C, assembly
language and Swift. It is the second most used operating system in personal
computers after Windows. The first version of macOS was launched by Apple
in 2001.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 13|Page


Let’s sees that the difference between Linux and mac:
S.N LINUX MAC

1. It is an open source operating It is a commercial operating


system system (closed source)
2. In linux, monolithic kernel is used MacOS is based the Xnu hybrid
micro kernel
3. It is used as OS, as server provide Mac is an operating system
platform to run other application provides platform to run other
application
4. It is customizable It is not possible to customize the
Mac OS
5. It supports many flavours like It does have any flavours.
RedHat, Ubuntu, Fedora, Suse,
etc,
6. It supports multiple desktop It supports only preinstalled
environments like GNOME, KDE, desktop environment
Mate, Budgie, Cinnamon, Deepin
etc,…

1.3.3 LINUX VS UNIX


Linux
Linux is an open source multi-tasking, multi-user operating system. It was
initially developed by Linus Torvalds in 1991. Linux OS is widely used in
desktops, mobiles, mainframes etc.
Unix
Unix is multi-tasking, multi-user operating system but is not free to use
and is not open source. It was developed in 1969 by Ken Thompson team at
AT&T Bell Labs. It is widely used on servers, workstations etc. Following are
the important differences between Linux and Unix.
Let’s sees that the difference between Linux and windows:

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 14|Page


S.N LINUX UNIX

1. It is an open source operating It is a licensed OS (closed source)


system
2. It is developed by linux community It was developed by AT and T Bell
of developers labs
3. Linux uses KDE and Gnome. Other Unix was initially a command
GUI supported are LXDE, Xfce, based OS. Most of the unix
Unity, Mate. distributions now have Gnome.
4. Bash (Bourne Again SHell) is Bourne Shell is default shell for
default shell for Linux. Unix.
5. Its flavours are RedHat, Ubuntu, Its flavours are SunOS, Solaris,
Suse, Kali Linux, etc,… HP-UX, AIX, Sco Unix, etc,…
6. Linux is used in wide varieties from It is mostly used on servers,
desktop, servers, smartphones to workstations or PCs.
mainframes.

1.4 SCHEDULING OF JOBS IN OPERATING SYSTEM


Job scheduling is the process of allocating system resources to many
different tasks by an operating system (OS). The system handles prioritized job
queues that are awaiting CPU time and it should determine which job to be
taken from which queue and the amount of time to be allocated for the job.
This type of scheduling makes sure that all jobs are carried out fairly and
on time. Most OSs like Unix, Windows, etc., include standard job-scheduling
abilities. A number of programs including database management systems
(DBMS), backup, enterprise resource planning (ERP) and business process
management (BPM) feature specific job scheduling capabilities as well.
1.5 PROCESS MANAGEMENT
Process management involves various tasks like creation, scheduling,
termination of processes, and a dead lock. Process is a program that is under
execution, which is an important part of modern-day operating systems. The
OS must allocate resources that enable processes to share and exchange
information.
It also protects the resources of each process from other methods and
allows synchronization among processes. It is the job of OS to manage all the
running processes of the system. It handles operations by performing tasks like
process scheduling and such as resource allocation.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 15|Page


1.6 PROCESS ARCHITECTURE
Stack
The stack stores temporary data like function parameters, returns
addresses, and localvariables.
Heap
It allocates memory, which may be processed during its run time.
Data
It contains the variable.
Text
It includes the current activity, which is represented by the value of
the Program Counter.

1.7 MEMORY MANAGEMENT IN OPERATING SYSTEMS


Memory management is the functionality of an operating system which
handles or manages primary memory and moves processes back and forth
between main memory and disk during execution. Memory management keeps
track of each and every memory location, regardless of either it is allocated to
some process or it is free. It checks how much memory is to be allocated to
processes. It decides which process will get memory at what time. It tracks
whenever some memory gets freed or unallocated and correspondingly it
updates the status.
The operating system takes care of mapping the logical addresses to
physical addresses at the time of memory allocation to the program. There are
three types of addresses used in a program before and after memory is
allocated –
1. Symbolic addresses
The addresses used in a source code. The variable names, constants,
and instruction labels are the basic elements of the symbolic address space.
2. Relative addresses
At the time of compilation, a compiler converts symbolic addresses into
relative addresses.
3. Physical addresses
The loader generates these addresses at the time when a program is
loaded into main memory.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 16|Page


1.8 SYSTEM CALLS IN OPERATING SYSTEMS
System call is a mechanism that provides the interface between a
process and the operating system. It is a programmatic method in which a
computer program requests a service from the kernel of the OS. System call
offers the services of the operating system to the user programs via API
(Application Programming Interface). System calls are the only entry points for
the kernel system. For example, if we need to write a program code to read data
from one file, copy that data into another file.
The first information that the program requires is the name of the two files,
the input and output files. In an interactive system, this type of program
execution requires some system calls by OS.
 First call is to write a prompting message on the screen.
 Second, to read from the keyboard, the characters which define the two files.

1.9 DAY TO DAY USAGE OF OPERATING SYSTEMS


The operating system is used everywhere nowadays especially such as
banks, schools, colleges, universities, govt. organizations, IT companies,
mobile, etc, …
No device can operate without an operating system because it controls
all the user’s commands. Linux /unix operating systems is used in bank because
it’s very secure operating systems.
Symbian OS, windows mobile, IOS and Android OS are used in mobile
phones operating systems as these operating systems are a lightweight
operating systems.

RESULT
The architecture and features of an operating system has been studied
successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 17|Page


EX.NO: 2 LINUX COMMANDS FILE SYSTEM
AIM
To study and implement about the various basic linux commands.

I. FILE RELATED COMMANDS

1. cat
 The cat command is used to create a file.
 The cat command is used to display the contents of a file.
 The cat command is also used merge multiple files into a single file
Syntax
$ cat > filename (Create a new file)
$ cat <filename> (Display the contents of file)
$ cat file1 file2 >file3 (merge the contents of file1, file2 into file 3)

1.1 File Creation & Display its Contents using cat command

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 18|Page


1. 2 Files Merging using cat command

2. ls command
 Listing files and directories
 The ls command is used to display the contents of a directory.
Syntax
$ ls  View the contents of directory

2. Displaying Files and Folders

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 19|Page


3. clear command
 This command is used to clear the terminal screen
 $ clear

II. DIRECTORY RELATED COMMANDS


1. mkdir
 This command is used create an empty directory in a disk

Syntax
$ mkdir <dname>

1.1 Empty Directory Creation

2. rmdir
 This command is used remove a directory from the disk

Rules for Directory Deletion

 Directory must be empty


 Directory can't be current working directory
Syntax
$ rmdir <dname>

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 20|Page


2.1 Empty Directory Deletion

3. cd
 This command is used to move from one directory to another directory.
Syntax
$ cd <dname>
3.1 Changing the Working Directory

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 21|Page


4. pwd
 pwd stands for "print working directory"
 This command is used to print the current working directory
Syntax
$ cd <dname>
4.1 Displaying Current Working Directory

III. General Purpose Commands


1. date command
 This command is used to display the current date with day, month, date,
time (24 Hrs clock) & year
 $ date
1. Output

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 22|Page


2. cal command
 Linux calendar
 This command is used to display the current month, all months of
particular year
 $ cal (Show the current month of current year)
 $ cal 2015 (Show all months in year 2015)
2.1 Displaying Current Month

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 23|Page


2.2 Displaying Entire Year

3. tty command
 The tty (teletype) command is used to print the current terminal name
 $ tty

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 24|Page


3.1 Displaying Terminal Name

RESULT
Thus the linux commands have been studied and executed
successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 25|Page


EX.NO: 3 SHELL PROGRAMMING BASICS

AIM
To execute the fundamentals of shell programming such as control flow
statements.

EXISTING PROBLEM
 It is not possible to perform more than one task at a time using shell
command
SHELL SCRIPTS (MULTITASKING)
 In order to solve the problems of shell command, the shell programming
is introduced here
 Doing more than one job at a time (multitasking)
 It is also called as shell programming

VARIABLES SECTION
 Names given to the memory location
 Shell program supports dynamic data typed system which means that
no need to use specific data type for variables declaration
Syntax

Variable-Name=Initial-Value

Example

a=10 # integer type


str=”Sachin” # string type
c=’G’ # character type
f=true # boolean value
readonly id=14 # integer constant

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 26|Page


I. EXAMPLE OF DATA TYPES IN SHELL CODE
SOURCE CODE
echo "------------------------------------"
echo "\tShell Data Types"
echo "------------------------------------"
# variables definition
a=19
b=15.45
c='S'
str="Sachin"
flag=true
# constant variable definition
readonly id=99
echo "Int\t\t\t\t-> $a"
echo "Float\t\t\t-> $b"
echo "Character\t\t-> $c"
echo "Name\t\t\t-> $str"
echo "Boolean\t\t\t-> $flag"
echo "Int Constant\t-> $id"

2. OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 27|Page


COMMENT LINE STATEMENTS

 Usually these statements are ignored by compiler or interpreter


 Like c/c++, shell supports two types of comment line statements. They
are
1. Single line statement
2. Multi line statements
1. Single line statement
 The single line statement is indicated by # symbol in shell program
Example

# This is single line statement

2. Multi line statements

 It is used to ignore more than one statements


 This is indicated by :’ ’ symbol in shell program
Example

:’ Variable Declarations
a=20
k=25

SELECTION STATEMENTS

1. Simple If statement

2. If else Statement

3. If else if Statement

4. Case Statement

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 28|Page


1. Simple If Statement
Syntax

if [ condition ]
then
true statement
fi

 It is an important to note that, the space should be given before and after
the operator symbol [
 You can use test keyword instead of the operator symbols [ ]
2. If else Statement
Syntax

if [ condition ]
then
true statement
else
false statement
fi

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 29|Page


3. If…elif…else Statement
Syntax

if [ condition ]
then
true statement
elif [ condition ]
then
true statement
else
false statement
fi

 It is an important to note that, the simple if, if else and if-elif-else should
be closed by fi keyword.
4. Case Statement
 It is equivalent to switch case statements in c language
 It is used to execute several statements based on the value of expression
 This is done by using the reserved word case
 It is an alternative option for if..elif..else statements
Syntax
case <variable> in
Pattern 1)
Commands / statements
;;
Pattern 2)
Commands / statements
;;

easc

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 30|Page


Where,

;;  represents the break part in case statements

LOOPING STATEMENTS

1. While loop (while)

2. Until loop (until)

3. For loop (for)

1. While loop
Syntax

while [ condition ]
do
true statement
done

Infinite While loop


 It is an important to note that, the colon (:) operator or true keyword is
used for creating an infinite loop
 The colon (:) operator is used instead of the operator symbols [ ]

II. EXAMPLE OF INFINITE LOOP USING WHILE LOOP

SOURCE CODE
while :
do
echo "Hello World"
done
(OR)
while true
do
echo "Hello World"

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 31|Page


done

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 32|Page


2. Until loop

 Here loop is executing until the condition is false

 If the condition becomes true it will exit from the loop

Syntax

until [ condition ]
do
true statement
done

III. EXAMPLE OF UNTIL LOOP


SOURCE CODE

echo "---------------------------------------------"
echo "\t\tUntil Loop Example"
echo "---------------------------------------------"
i=1
until [ $i -gt 5 ] Here the looping statements are executed
do until the condition becomes fail like 1>5,
echo $i 2>5, 3>5, 4>5, 5>5
i=`expr $i + 1`
done

This loop will terminate whenever the


condition becomes true like 6>5

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 33|Page


OUTPUT

3. For loop
Syntax

for variable in w1 w2 … wn
do
true statement
done

Where,
Variable can be any user defined name
w1 w2 …wn  list of the values separated by spaces

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 34|Page


IV. EXAMPLE OF FOR LOOP
SOURCE CODE

echo "-------------------------------------"
echo "\t For Loop Example"
echo "-------------------------------------"
for i in 12 14 15 17 18 21
do
echo $i
done

OUTPUT

V. CHARACTERS AND STRING RETRIEVAL USING FOR LOOP


SOURCE CODE

echo "-----------------------------------------------------------"
echo "\t Char & String Retrieval using for loop"
echo "-----------------------------------------------------------"
for i in 'Sachin' 'B' "C" "D" ‘E’
do
echo $i
done

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 35|Page


OUTPUT

VI. DISPLAYING FILES AND DIRECTORIES USING FOR LOOP


SOURCE CODE

echo "---------------------------------------------------------------"
echo "\t Listing Files and Folder using for loop"
echo "---------------------------------------------------------------"
# get all the files and store them to variable
fset=`ls`
Store list of files to the variable fset using
k=1
ls command.
# loop the variable fset
for i in $fset
do
echo "$k. $i" k=k+1 or k++
k=`expr $k + 1`
done

Command Substitution:
Storing the output of command to a user defined variable.
This is done by using the operator `command` or $(command)

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 36|Page


OUTPUT

VII. FACTORIAL OF A NUMBER


Language : shell (.sh)
Editor : replit.com (Online Linux Terminal)
OS : Windows 10

SOURCE CODE

echo "--------------------------------------------"
echo "\t\tFactorial Program"
echo "--------------------------------------------"
echo "Enter a number : "
read n
i=0
f=1
while [ $i -lt $n ]

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 37|Page


do
# increment i by 1
i=`expr $i + 1`
f=`expr $f \* $i`
done
echo "The Factorial of $n is : $f"

OUTPUT

C STYLE CODING IN SHELL


 In shell, we can use c style coding for looping statements and
expressions
 The expressions are defined by $(exp). Here each is also closed by ()
symbol.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 38|Page


VIII. FACTORIAL OF A NUMBER USING C-STYLE
SOURCE CODE

echo "------------------------------------------------"
echo "\t\tFactorial Program- C Style"
echo "------------------------------------------------"
echo "Enter a number : "
read n
i=1
f=1
# while loop
while [ $i -le $n ]
do
# expression 1 in c-style
f=$((f*i))
# expression 2 in c-style
i=$((i+1))
done
echo "Factorial of $n is $f"

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 39|Page


IX. REVERSE OF A NUMBER
SOURCE CODE

echo "--------------------------------------------"
echo "\t\tReverse of Number"
echo "--------------------------------------------"
echo "Enter a number : " Read a number
read n
duplicate=$n
while (n!=0)
res=0
while [ $n -ne 0 ]
do rem=n%10
# find the reminder
rem=`expr $n % 10`
res=res*10
# multiply reverse number with 10
res=`expr $res \* 10`
# add the resultant number with remainder number
res=`expr $res + $rem`
# divide n by 10
n=n/10
n=`expr $n / 10`
done
echo "The Reverse Number of $duplicate is $res"

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 40|Page


OUTPUT

X. ARMSTRONG NUMBER
SOURCE CODE

echo "--------------------------------------------"
echo "\t\tArmstrong Number"
echo "--------------------------------------------"
echo "enter a number"
read n
# variables declarations
dup=$n while (n!=0)
arm=0
# while loop
while test $n -ne 0
rem=n%10
do
# find remainder of a number
rem=`expr $n % 10`
# multiply rem with three times rem=(rem*rem*rem)

rem=`expr $rem \* $rem \* $rem`


# add the resultant remainder with arm variable

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 41|Page


arm=`expr $arm + $rem`
# divide n by 10
n=`expr $n / 10`
n=n/10
done
if [ $dup -eq $arm ]
then
echo "Given Number $dup is Armstrong Number"
else
echo "Given Number $dup is not Armstrong Number"
fi

OUTPUT

XI. MENU DRIVEN PROGRAM


SOURCE CODE

while [ true ]
do
echo "-------------------------------------"
echo "\t\t Menu Program"
echo "-------------------------------------"
echo "1. View Files \t 2.Date"
echo "3. Users List \t4.Calendar"
echo "5. Exit"

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 42|Page


echo "\tEnter ur choice : "
read ch
#switch case
case $ch in
1) ls;;
2) date;;
3) w;;
4) cal;;
5) exit;;
esac
# read choice from user for continuation of program execution
echo "Do you want to continue : Press Yes/No"
read ch
if [ $ch = "yes" ] || [ $ch = "Yes" ] || [ $ch = "YES" ]
then
continue
else
exit
fi
done

NOTE

 It is an important to note that, the single equal operator (=) is used for
string comparison and the symbol –eq or == is used for number
comparison in the shell program.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 43|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 44|Page


OUTPUT – (CON)

COMMAND LINE ARGUMENTS (POSITIONAL PARAMETERS)

 Process of passing the input arguments to the program at the time of


execution is called as command line arguments
 In shell, this is done with help of $ symbol

S.N POSITIONAL DESCRIPTION


PARAMETERS
1. $0 Indicates the filename itself
2. $1 Indicates the first argument
3. $2 Indicates the second argument

4. $* Represents the total number of input arguments
which are submitted to the shell program
5. $# Shows the count of total number of arguments
passed to the shell program

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 45|Page


I. EXAMPLE OF COMMAND LINE INPUTS
SOURCE CODE
echo "----------------------------------------------"
echo "\t\tCommand Line Arguments (Input)"
echo "----------------------------------------------"
a=$1
b=$2
# check whether the command line arguments are submitted or not
if [ $# -ne 0 ]
then This is equivalent to if [ $# != 0 ]

r=`expr $a + $b`
echo "Sum is: $r"
else
echo "No inputs are submitted...Please submit the CMD inputs..."
fi

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 46|Page


II. EXAMPLE OF COMMAND LINE INPUTS – MUCH ARGUMENTS
SOURCE CODE
echo "-------------------------------------------------"
echo "\t\tCommand Line Arguments"
echo "-------------------------------------------------"
# check whether the command line arguments are submitted or not
if [ $# -ne 0 ]
then
echo "Total Input Arguments are Submitted: $#"
for i in $*
This is equivalent to if [ $# != 0 ]
do
echo $i
done
else
echo "No inputs are submitted...Please submit the CMD inputs..."
fi
OUTPUT

RESULT
Thus the basics of shell programming was executed successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 47|Page


EX.NO: 4 SHELL SCRIPTING – OPERATORS, FUNCTIONS
AIM
To practice the different types of operators using shell programming
OPERATORS
 A special symbol which is used to perform the various tasks such as
arithmetic operations, relational operations, logical operations, file testing
operations, comparisons, etc, …

ARITHMETIC OPERATORS
S.N OPERATOR DESCRIPTION
1. + Addition
2. - Subtraction
3. * Multiplication
4. / Division

EXPRESSION IN SHELLS
 Shell provides two options for performing expressions in shell scripts.
They are

1. Using expr command  Shell style expr

2. Using double braces ()  C Style $(exp)

NOTE
 It is an important to note that, the operator * does not provide the
multiplication in shell expression using expr command. Because in shell,
the operator * means wild card characters.

 So, the backward slash followed by * symbol \* is to provide the


multiplication expression in shell expression using expr command.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 48|Page


I. EXAMPLE OF ARITHMETIC OPERATIONS USING EXPR COMMAND
SOURCE CODE
echo "-----------------------------------------------------------------"
echo "\tArithmetic Operations using expr command"
echo "-----------------------------------------------------------------"
echo "Enter the number 1: "
read a
echo "Enter the number 2: "
read b
# performing arithmetic operations using expr command
r1=`expr $a + $b`
r2=`expr $a - $b`
r3=`expr $a \* $b`
r4=`expr $a / $b`
# print the results
echo "Add: \t$r1"
echo "Sub: \t$r2"
The usage of * in expr command does not directly
echo "Mul: \t$r3" support for multiplication. Because it gives different
echo "Div: \t$r4" meanings. So the backward slash with * symbol
provides the multiplication in the expr command.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 49|Page


OUTPUT

II. EXAMPLE OF ARITHMETIC OPERATIONS USING C STYLE


SOURCE CODE
echo "-----------------------------------------------------------------"
echo "\tArithmetic Operations using C-Style"
echo "-----------------------------------------------------------------"
echo "Enter the number 1: " The Syntax is $(e1, e2,..en).
read a Each expression e1, e2, ..en can be
echo "Enter the number 2: " closed by ()

read b
# performing arithmetic operations using expr command
r1=$((a+b))
r2=$((a-b))
r3=$((a*b))
r4=$((a/b))
# print the results
echo "Add: \t$r1"
echo "Sub: \t$r2"
echo "Mul: \t$r3"
echo "Div: \t$r4"

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 50|Page


OUTPUT

RELATIONAL OPERATORS
RELATIONAL OPERATORS FOR NUMBERS [ using $() ]
S.N OPERATOR DESCRIPTION
1. == Equal
2. != Not Equal
3. < Lesser than
4. <= Lesser than or Equal to
5. > Greater than
6. >= Greater than or Equal to

NUMERIC COMPARISON OPERATORS FOR NUMBERS


S.N OPERATOR DESCRIPTION
1. -eq Equal
2. -ne Not Equal
3. -gt Greater than
4. -ge Greater than or Equal to
5. -lt Lesser than
6. -le Lesser than or Equal to

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 51|Page


RELATIONAL OPERATORS FOR STRINGS [ using if ]
S.N OPERATOR DESCRIPTION
1. = Equal
2. != Not Equal
3. \< Lesser than
4. \> Greater than

III. EXAMPLE OF RELATIONAL OPERATORS USING C STYLE


SOURCE CODE
echo "-----------------------------------------------------------------"
echo "\tRelational Operators using C-Style"
echo "-----------------------------------------------------------------"
echo "Enter the number 1: "
read a
echo "Enter the number 2: "
read b
# performing relational operators using C style $()
r1=$((a==b))
r2=$((a!=b))
r3=$((a<b))
r4=$((a<=b))
r5=$((a>b))
r6=$((a>=b))
# print the relational results
echo "Equal \t\t\t\t\t\t: $r1"
echo "Not Equal \t\t\t\t\t: $r2"
echo "Lesser than \t\t\t\t: $r3"
echo "Lesser than or Equal to \t: $r4"
echo "Greater than \t\t\t\t: $r5"
echo "Greater than or Equal to \t: $r6"

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 52|Page


OUTPUT

IV. EXAMPLE OF RELATIONAL OPERATORS FOR STRINGS


SOURCE CODE
echo "-----------------------------------------------------------------"
echo "\tRelational Operators for Strings"
echo "-----------------------------------------------------------------"
echo "Enter the name 1: "
read a
echo "Enter the name 2: "
read b
# performing relational operators for strings
if [ $a = $b ]
then
echo "----------Equal Results------------------"
echo "Both Strings are Equal"
else
echo "----------Equal Results------------------"
echo "Both Strings are NOT Equal"
fi
if [ $a != $b ]

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 53|Page


then
echo "----------NOT Equal Results------------------"
echo "Both Strings are NOT Equal"
else
echo "----------NOT Equal Results------------------"
echo "Both Strings are Equal"
fi
if [ $a \> $b ]
then
echo "----------Greater Results------------------"
echo "$a is Greater than $b"
else
echo "----------Greater Results------------------"
echo "$b is Greater than $a"
fi
if [ $a \< $b ]
then
echo "----------Lesser Results------------------"
echo "$a is Lesser than $b"
else
echo "----------Lesser Results------------------"
echo "$b is Lesser than $a"
fi

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 54|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 55|Page


LOGICAL OPERATORS (BOOLEAN OPERATORS)
S.N OPERATOR OPERATORS IN DESCRIPTION
SHELL
1. Logical AND && Binary operator which returns
true if both the operands are
true otherwise returns false
value
2. Logical OR || Binary operator which returns
true if one of the operand or
both is true otherwise returns
false value
3. Not Equal to ! Unary operator returns true if
the operand is false and
returns true if the operand is
true

V. EXAMPLE OF LOGICAL AND OPERATOR


SOURCE CODE
echo "----------------------------------------"
echo "\tLogical AND Operator"
echo "----------------------------------------"
echo "Enter the number 1: "
read a
echo "Enter the number 2: "
read b
echo "Enter the number 3: "
read c
if [ $a -gt $b ] && [ $a -gt $c ]
then
echo "$a is bigger than $b and $c"
elif [ $b -gt $c ]
then
echo "$b is bigger than $a and $b"
else

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 56|Page


echo "$c is bigger than $a and $b"
fi

OUTPUT

FILE TYPE OPERATORS


S.N OPERATOR DESCRIPTION
1. -f Returns true if exists and if it is a regular file
(.txt, .c. sh, etc,…)
2. -d Returns true if exists and if it is a directory
3. -e Returns true if exists
4. -z Returns true if file is empty (file has zero
length)
5. -r Returns true if exists and is readable mode
6. -w Returns true if exists and is writable mode
7. -x Returns true if exists and is executable mode

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 57|Page


VI. EXAMPLE OF FILE TEST OPERATORS
SOURCE CODE
echo "-----------------------------------------------------------------"
echo "\tFile Testing Operator"
echo "-----------------------------------------------------------------"
echo "Enter the file name : "
read fp
if [ -e $fp ]
then
echo "Object Exists..."
if [ -f $fp ]
then
echo "It is a regular file..."
echo "Contents:"
echo $(cat $fp)
elif [ -d $fp ]
then
echo "It is a directory..."
dpath=`pwd`/$fp
echo $dpath
echo "Contents of Directory: "
for i in $(ls $dpath)
do
echo $i
done
else
echo "It is a special file..."
fi
else
echo "Object does not exists..."
fi

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 58|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 59|Page


DIRECTORIES
S.N OPERATOR DESCRIPTION
1. ls (OR) ls . Shows the list of files and folders in current
directory
2. ls .. Shows the list of files and folders in parent
directory
3. ls / Shows the list of files and folders in root
working directory
4. ls -l Shows the files and folders in long listing
format
5. ls -s Shows the size of files and folders in current
directory

VII. LISTING FILES AND FOLDERS IN ROOT DIRECTORY


SOURCE CODE
(test.sh)
echo "----------------------------------------------------"
echo "\tFiles and Folders in Root Directory"
echo "----------------------------------------------------"
for i in $(ls /)
do
echo $i Root Path: $ ls /

done

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 60|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 61|Page


VIII. LISTING FILES AND FOLDERS IN PARENT DIRECTORY
SOURCE CODE
echo "----------------------------------------------------"
echo "\tFiles and Folders in Parent Directory"
echo "----------------------------------------------------"
for i in $(ls ..)
do
Path of Parent Directory: $ ls ..
echo $i
done

OUTPUT

IX. LISTING FILES AND FOLDERS IN CURRENT DIRECTORY


SOURCE CODE
echo "----------------------------------------------------"
echo "\tFiles and Folders in Current Directory"
echo "----------------------------------------------------"
for i in $(ls)
do
echo $i Path of Current Directory: $ ls
done

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 62|Page


OUTPUT

LIST FILES IN LONG FORMAT


 The command ls -l provides the detailed format of showing the files and
folders in current file system.

1. Content Permissions

2. Number of links to the content

3. Owner of the content

4. Group onwer of the content

5. Size of the content (in bytes)

6. Last modified date / time

7. Name of the file / directory name

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 63|Page


Long Listing of Files and Folders

CONTENT PERMISSION
 In content permission, the column 1 indicates the file type. They are

 - means for regular file

 d means for directory

 b means for special block file

 c means for special character file

 In content permission, the next column indicates the file permissions


such as read, write and execute

 Read  represents the read mode which is code value 4

 Write  represents the write mode which is code value 2

 Execute  represents the execute mode which is code value 1.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 64|Page


SHELL FUNCTION

 Shell program supports the function which is used to implement the


variables as well as execute the linux commands.
Syntax1

function <name>
{
# user code
}

Example

function show
{
# user code
}

Syntax2

<function-name>()
{
# user code
}

Example

show()
{
# user code
}

CALLING FUNCTION
 Shell function can be called using its name only.
 The operation () should not be used while calling the function.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 65|Page


Syntax

$ function-name

Example

$ show

I. EXAMPLE OF SHELL FUNCTION


SOURCE CODE
echo "------------------------------------------"
echo "\t\tShell Function"
echo "------------------------------------------"
disp()
{
The operator symbol () is not allowed while
echo "Good Morning ..."
calling the shell function.
}
# calling function
disp

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 66|Page


SHELL FUNCTION WITH ARGUMENTS
 Shell function supports the arguments
 The arguments are given after the function name while calling the
function
 Each argument is separated by space
 The positional parameters like $1, $2, etc… will receive the values of
function arguments inside the function definition

II. EXAMPLE OF SHELL FUNCTION WITH ARGUMENTS


SOURCE CODE
echo "--------------------------------------------------------"
echo "\t\tShell Function with Arguments"
echo "--------------------------------------------------------"
# creating a shell function
disp()
{
a=$1
b=$2
rs=`expr $a + $b`
echo "Sum is: $rs"
}
# calling function with arguments
disp 12 21

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 67|Page


SHELL FUNCTION WITH RETURN STATEMENTS
 Like c language, shell function returns the values
 The return keyword is used to return the values in the shell function
 The returned result of calling function can be obtained using the special
symbol $? (by default, the return values of the function will be stored to
the built-in variable $?)
NOTE
 It is an important to note that, the shell function will return a single value.

III. EXAMPLE OF SHELL FUNCTION WITH RETURN VALUE


SOURCE CODE
echo "-------------------------------------------------------------"
echo "\t\tShell Function with Return Value"
echo "-------------------------------------------------------------"
a=12
b=23
rs=0
# shell function
disp()
{
rs=`expr $a + $b`
# return the variable
return $rs
}
# calling function
disp
# get the return value from function using $?
k=$?
echo "Sum is: $k"

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 68|Page


OUTPUT

COMMAND SUBSTITUTION
 In shell, assigning the built-in command to a user defined variable is
called as command substitution

 This is done using the special symbol `command-name` or $(command-


name)

Syntax1

Variable-Name=`command-name`

Example

files=`ls` # the output of ls command is stored to the


variable called files.

dirpath=”test”
files=`ls $dirpath ` # the contents of test directory are stored
to the variable called files

Syntax 2

Variable-Name=$(command-name)

Example

files=$(ls) # the output of ls command is stored to the


variable called files.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 69|Page


I. EXAMPLE OF COMMAND SUBSTITUTION
SOURCE CODE
echo "-------------------------------------------"
echo "\tCommand Substitution"
echo "-------------------------------------------"
# date command Substitution
rs=`date`
# k=$(date)
# print the output of date command via variable
echo "Current Date: \n"$rs

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 70|Page


II. COMMAND SUBSTITUTION-FILE COPYING BETWEEN DIRECTORIES
SOURCE CODE
echo "-----------------------------------------------------"
echo "\t\tCopying Files B/W Directories"
echo "-----------------------------------------------------"
# path of source directory Command Substitution using the
path="/home/runner/OS-Lab/d1" symbol ` `

# k=$(ls $path)
src=`ls $path` Path of Source Directory (d1). Parent
Path can be get using pwd command.
path of target directory
tar="/home/runner/OS-Lab/d5"
# for loop
for i in $src Path of Target Directory (d5).

do
cp $i $tar
echo "$i is successfully copied to $tar/$i"
done
echo "-----------------------------------------------------"

OUTPUT

RESULT
Thus the operators and shell functions of the shell programming have
been executed successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 71|Page


EX.NO: 5 SHELL ARRAYS
AIM
To practice the arrays in shell programming.
SHELL ARRAY
 Array is a set of elements which are having same type or different type
 It is an example of linear data structures (sequential data structure)
 It is accessed by the index number which starts from 0 to n-1
 It supports the storage, retrieval, insertion, deletion and updation
 In shell, the array can be created with help of the special operator
symbol () instead of square operator []
 Unlike other compiled languages c/c++/c#/java, the shell follows the
dynamic data typed system. So no need to mention the data type in the
creation of an array.
Syntax

User-defined-name = (Element 1 Element 2 …Element n)

Where,
Element 1, Element 2, …Element n can be Same Type or Different
Type.
Example

arr=(12 34 59) // homogenous collection


arr=(“Sachin” 12.41 55 true) // heterogeneous

Length
 Array length can be done by using the special symbol # followed by @
or * symbol along with array name
 It is very important to note that, the curly braces operators {} are used
for accessing the array in shell
Syntax

{#<array-name>[@]}

(OR)

{#<array-name>[*]}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 72|Page


Example

ls=(12 34 55 99)
len=${#ls[@]}
(OR)
len=${#ls[*]}

Accessing Individual array contents


 The contents of the array can have accessed by using its index location
Example

ls[0]  12
ls[1]  32

Printing Individual Element


 The individual element of an array can be displayed using the curly
braces {} along with array name
Syntax

${arrayname[index-number]}

Example

echo ${ls[1]} // display the second element


echo ${ls[3]} // display the fourth element

Accessing Entire array contents


 The entire array elements can be called using the star symbol * or @
with array name.
 It is an important to note that, if the index number is * or @, the whole
elements of the array are referenced.
Example

${ls[*]}  contains the entire array elements


echo ${ls[*]}  show the array contents at the same time.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 73|Page


OR

${ls[@]}  contains the entire array elements


echo ${ls[@]}  show the array contents at the same time.

Commands to check the Shell Types


$ cat /etc/shells

I. EXAMPLE OF ARRAY CREATION FOR HOMOGENOUS TYPE


(/home/runner/Latest-Shells-21/arr1.sh)
SOURCE CODE
echo "-------------------------------------------------"
echo "Shell Array for Same Type of Elements"
echo "-------------------------------------------------"
# Array Creation
lb=(12 45 77 99 88)
# print the contents of array at the same time
echo "Array Contents using name"
echo ${lb[*]}
Same type elements of array.
# print the length of the array
echo "Length of the Array: ${#lb[@]}"
echo "Array Contents using for loop"
echo "-------------------------------------------------"
Display the array contents at the same time
using the name.
IT7411 – OS LABORATORY (4/8 B.TECH – IT) 74|Page
# print the contents of array
for i in ${lb[*]}
do
echo $i
done Display the array contents one by one
using for loop.

OUTPUT

II. EXAMPLE OF ARRAY CREATION FOR HETEROGENEOUS TYPE


(/home/runner/Latest-Shells-21/arr2.sh)
SOURCE CODE
echo "-------------------------------------------------"
echo "Shell Array for Different Type of Elements"
echo "-------------------------------------------------"
# Array Creation
lb=("Shiva" 21 72.93 True) Different type elements of
array.
# print the contents of array at the same time
echo "Array Contents using name"
echo ${lb[*]} Display the array contents at the
# print the length of the array same time using the name.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 75|Page


echo "Length of the Array: ${#lb[@]}"
echo "Array Contents using for loop"
echo "-------------------------------------------------"
# print the contents of array
for i in ${lb[*]}
do
echo $i Display the array contents one by one
done using for loop.

OUTPUT

III. INDEX BASED ARRAY CREATION FOR HETEROGENEOUS TYPE


(/home/runner/Latest-Shells-21/arr3.sh)
SOURCE CODE
echo "-------------------------------------------------"
echo "Array Creation using Index"
echo "-------------------------------------------------"
# Empty array Empty array creation
ls=()
# store the elements to array using index number
ls[0]=12

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 76|Page


Storing elements to array using
ls[1]=21 index number.
ls[2]='M'
ls[3]=True
ls[4]="Rohit"
# print the contents of array at the same time
echo "Array Contents using name"
echo ${ls[*]}
# print the length of the array
echo "Length of the Array: ${#ls[@]}"
echo "Array Contents using for loop"
echo "-------------------------------------------------"
# print the contents of array
for i in ${ls[*]} Printing the array length.
do
echo $i
done

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 77|Page


IV. DISPLAYING LINUX COMMANDS USING ARRAY
(/home/runner/Latest-Shells-21/arr4.sh)
SOURCE CODE

echo "-------------------------------------------------"
echo "Shell Array for Same Type of Elements"
echo "-------------------------------------------------"
# Array Creation
lb=()
# assigning linux commands to the each location of array
lb[0]=$(ls)
lb[1]=$(date)
lb[2]=`cal`
lb[3]=`cat /etc/shells`
# print the length of the array
echo "Length of the Array: ${#lb[@]}"
echo "Array Contents using for loop"
echo "-------------------------------------------------"
# print the contents of array
for i in ${lb[*]}
do
echo $i
done

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 78|Page


DISPLAYING THE OUTPUT OF LINUX COMMANDS

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 79|Page


DISPLAYING THE OUTPUT OF LINUX COMMANDS – (CONTINUE)

RESULT
Thus the arrays using shell programming have been executed
successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 80|Page


EX.NO: 6 PROCESS SYSTEM CALLS – FORK, EXIT, WAIT

AIM
To practice the system calls such as fork, wait, exit using linux c
programming.
SYSTEM CALLS
 It is an interface between process and kernel

 It is way for programs to interact with OS

 Five different types of system calls are available. They are

1. Process Control

2. File Management

3. Device Management

4. Information Management

5. Communication

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 81|Page


1. Process Control
 This system calls perform the task of process creation, process
termination, etc.

Functions
 End and Abort
 Load and Execute
 Create Process and Terminate Process
 Wait and Signed Event
 Allocate and free memory
2. File Management
 It handles file manipulation jobs like creating a file, reading, and writing,
etc.

Functions
 Create a file
 Delete file
 Open and close file
 Read, write, and reposition
 Get and set file attributes
3. Device Management
 It performs the job of device manipulation like reading from device
buffers, writing into device buffers, etc.

Functions
 Request and release device
 Logically attach/ detach devices
 Get and Set device attributes

4. Information Management
 It handles information and its transfer between the OS and the user
program.

Functions
 Get or set time and date

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 82|Page


 Get process and device attributes
5. Communication
 These types of system calls are specially used for interprocess
communications.

Functions
 Create, delete communications connections

 Send, receive message

 Help OS to transfer status information

 Attach or detach remote devices


PROCESS CONTROL SYSTEM CALLS
 It deals with process creation, process termination, etc, …

Examples
S.N Linux Windows Description
1. fork() CreateProcess() Create a child process
2. exit() ExitProcess() Terminate the process
3. wait() WaitForSignalObject() Wait for the child process
termination

fork()
 It is an important system calls which is used to create a new process in
the OS

 The newly created process is called as child process and caller of the
child process is called as parent process

 It takes no arguments and returns the process ID

 It is called once but returns twice (once in parent and once in the child)

 The new process gets a copy of the current program, but new process id
(pid). The process id of the parent process (the process that called fork())
is registered as the new processes parent pid (ppid) to build a process
tree.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 83|Page


 It is an important to note that, Unix / Linux will make an exact copy of the
parent's address space and give it to the child. Therefore, the parent and
child processes have separate address spaces.

 It returns the following values:

 Negative  new process creation was unsuccessful

 Zero  returned to child process

 Positive  returned to parent (caller) process

Child Process
 The newly created process is called as child process

 It is identified by the return code is 0

Parent Process
 The caller of the newly created process is called as parent process

 It is identified by the return code is positive value

Formula
Total number of processes (T) : 2n
Total number of Child processes (C) : 2n-1
Total number of Child processes (P) : T-C
NOTE
 After the fork(), both parent and child processes are running
simultaneously

 The newly created process is called as child process which is identified


by the return code is 0 and the caller of the child process is called as
parent process which is identified by positive value (>0)

 Program statements before fork() is common for both child and parent
processes but after fork() call, the rest of the program instructions will be
allocated separately for child and parent process

 Child and parent processes don’t share common address space. They
are having own memory address space. So if there are any changes in
child process won’t reflect the parent process. Similarly, if there are any
changes in parent processes won’t reflect the child process.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 84|Page


WHICH PROCESS RUNS FIRST (b/w parent and child process)
 It an important to note that, there is no rule about which process runs first
between parent and child processes.

 As soon as a process is ready for execution (i.e. the fork system call
returns), it may run according to the scheduling configuration (priority,
scheduler chosen, etc.).

 Depending on how the process is added to the scheduler, either process


may be scheduled first after returning from fork.

REQUIRED HEADER FILES


1. #include<stdio.h>
 This header file is used for printf(), scanf(), etc, …

2. #include<unistd.h>
 This header file is used for fork(), getpid(), getppid(), etc, …

3. #include<sys/types.h>
 This header file is used for pid_t, etc, …

4. #include<sys/wait.h>
 This header file is used for wait(), etc, …

5. #include<stdlib.h>
 This header file is used for exit(), etc, …

TOOLS SUPPORT
Compiler : gcc compiler (gcc <filename>.c)
Execution : ./a.out (assembly output)
OS : Linux OS platform
Terminal : Online linux terminal (www.replit.com)

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 85|Page


I. EXAMPLE OF SINGLE FORK
(fork1.c)
SOURCE CODE
#include<unistd.h> Total Number of Processes are  2n
#include<stdio.h>
 21
int main()
2
{
printf("-----------------------------------------\n");
printf("\tSimple Fork()\n");
printf("-----------------------------------------\n");
// calling fork()
fork();
printf("Hello World\n");
return 0;
}

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 86|Page


Pictorial Representation

 When the child process is created, both the parent process and the child
process will point to the next instruction (same Program Counter) after
the fork().

 In this way the remaining instructions or C statements will be executed


the total number of process times, that is 2n times, where n is the number
of fork() system calls

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 87|Page


II. CALLING DOUBLE FORK
SOURCE CODE
Total Number of Processes are  2n
#include<unistd.h>
 22
#include<stdio.h>
4
int main()
{
printf("------------------------------------------------\n");
printf("\tCalling Double Fork()\n");
printf("------------------------------------------------\n");
// calling double fork()
fork();
fork();
printf("Good Morning\n");
return 0;
}

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 88|Page


III. CALLING TRIPLE FORK
SOURCE CODE
Total Number of Processes are  2n
#include<unistd.h>
 23
#include<stdio.h>
8
int main()
{
printf("--------------------------------------------\n");
printf("\tCalling Triple Fork()\n");
printf("--------------------------------------------\n");
// calling triple fork()
fork();
fork();
fork();
printf("Welcome to Chennai\n");
return 0;
}

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 89|Page


IV. PRINT THE RETURNED VALUE OF CHILD AND PARENT PROCESSES
USING FORK
SOURCE CODE
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
int main() This header supports the pid_t
{
pid_t id;
printf("-----------------------------------------\n");
printf("\tReturn Code of Parent & Child\n");
printf("-----------------------------------------\n");
// calling fork()
Child Process: It is identified by 0
id=fork();
if(id==0)
{
printf("Child Process is calling ...\n");
printf("Returned Value of Child Process : %d\n",id);
}
Parent Process: It is identified by >0
else
{
printf("Parent Process is calling ...\n");
printf("Returned Value of Parent Process : %d\n",id);
}
return 0;
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 90|Page


OUTPUT

Usage of getpid() and getppid()


 Two major functions which are used to get the process ids. They are

1. getpid()

2. getppid()

1. getpid()
 It is a built-in function and available in #include<unistd.h> header file

 It is used to return the process ID of child process (newly created process)

 Return value: pid_t

2. getppid()
 It is a built-in function and available in #include<unistd.h> header file

 It is used to return the process ID of parent process (caller of the newly


created process)

 Return value: pid_t

pid_t
 It stands for process id type and built-in variable to store the process ids
of parent and child function

 It is the type of the process ID which returns an unsigned integer value.

 It is available in #include<sys/types.h>

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 91|Page


V. DISPLAY THE PROCESS ID (PID) OF PARENT AND CHILD
PROCESSES USING GETPID() AND GETPPID()
SOURCE CODE
#include<unistd.h>
#include<stdio.h>
#include <sys/types.h>
int main()
{
int id;
printf("-----------------------------------------\n");
printf("\tProcess ID of Parent & Child\n");
printf("-----------------------------------------\n");
// calling fork()
id=fork();
if(id==0)
{
printf("Child Process is calling ...\n");
printf("Process ID (PID) of Child Process : %d\n",getpid());
}
else
{
printf("Parent Process is calling ...\n");
printf("Process ID (PID) of Parent Process : %d\n",getppid());
}
return 0;
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 92|Page


OUTPUT

Wait()
 It is system call and available in #include<sys/wait.h> file

 It blocks the current process (calling process), until one of its child
processes terminate or a signal is received

 It takes one argument which is the address of an integer variable (stores


the information of the process) and returns the process ID (PID) of
completed child process

 Return type: pid_t

 If only one child process is terminated (finished its execution), then it


returns the process ID of the terminated child process

 If more than one child processes are terminated, then it returns process
ID of any terminated arbitrary child process.

The execution of wait() could have two possible situations.


1. If there are at least one child processes running when the call to wait() is
made, the caller will be blocked until one of its child processes exits. At
that moment, the caller resumes its execution.

2. If there is no child process running when the call to wait() is made, then
this wait() has no effect at all. It returns -1 immediately.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 93|Page


NOTABLE POINTS
 wait(NULL) will block the parent process until any of its children has
finished their execution (parent process will be blocked until child process
returns an exit status to the operating system which is then returned to
parent process)

 If child finishes before parent reaches wait(NULL) then it will read the exit
status, release the process entry in the process table and continue
execution until it finishes as well.

 Wait can be used to make the parent process wait for the child to
terminate (finish) but not the other way around

 Wait(NULL) simply making the parent wait for the child.

 On success, wait() returns the process ID of terminated child process


while on failure it returns -1

 Once child process finishes, parent resumes and prints the rest of the
statements of parent process

exit()
 It is system call and available in #include<stdlib> file

 It takes only one parameter which is exit status as a parameter

 It is used to close all files, sockets, frees all memory and then terminates
the process.

 The parameter 0 indicates that the termination is normal.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 94|Page


VI. EXAMPLE OF WAIT AND EXIT SYSTEM CALLS
SOURCE CODE
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t pd;
printf("-----------------------------------------------\n");
printf("\twait() and exit()\n");
printf("-----------------------------------------------\n");
// execution of fork() call
if (fork()== 0)
{
printf("Child is calling...\n");
// normal termination
exit(0);
}
else
{
// get the PID of terminated child process
pd = wait(NULL);
printf("Parent is calling...\n");
// print the process IDs of parent and child processes
printf("Parent PID\t: %d\n", getppid());
printf("Child PID\t: %d\n", pd);
}
return 0;
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 95|Page


OUTPUT

VII. SUM OF NUMBERS IN ARRAY USING CHILD AND PARENT


PROCESS
Task
Write a linux c program to find the sum of the numbers in array in child process
and execute the parent process after the execution of child process using
system calls.
Used System calls:
fork(), wait()
SOURCE CODE
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
int i,a[]={1,5,7,8,9};

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 96|Page


int s=0;
printf("---------------------------------------------------------------------------\n");
printf("\tSum of Numbers in Child and Execution of Parent after the
child\n");
printf("---------------------------------------------------------------------------\n");
// create new process by fork and return the value in p
int p=fork();
// if the returned value is negative value (unsuccessful status)
if(p<0)
{
printf("Failed to create a new Process ...\n");
exit(0);
}
// if the returned value is equal to 0 (checking child process)
else if(p==0)
{
printf("Child Process is calling...\n");
for(i=0;i<5;i++)
{ Wait() System call: wait parent until
s=s+a[i]; child has to terminate.
}
printf("The result is: %d\n",s);
printf("Child Process is completed...\n");
}
// if the returned value is positive (checking parent process)
else
{
wait(NULL);
printf("Parent Process is calling after the Child Process ...\n");
}
return 0;
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 97|Page


OUTPUT

RESULT
Thus the types of process system calls have been executed
successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 98|Page


EX.NO: 7 INTERPROCESS COMMUNICATION USING PIPE
AIM
To work with interprocess communication using pipe in linux c
programming.
IPC
 IPC stands for Inter Process Communication
 It is one of the mechanism provided by the OS which allows processes
to communicate with each other and synchronize their action
 Examples: Message Queue, Signals, Shared Memory, Pipes, etc,…

Process (P1) Process (P2) … Process


(Pn)

IPC

EXAMPLES TECHNIQUES OF IPC


 Shared Files

 Shared Memory

 Pipes (Named and Unnamed Pipes)

 Message Queues

 Sockets

 Signals

PIPES
 Pipe provides the communication between processes on same computer
or different computer or across the network

 It is classified as two types. They are

1. Unnamed Pipe (PIPE)

2. Named Pipe (FIFO)

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 99|Page


Pipe Symbol
 The output of one command (read) can be given as the input of next
command (write) that is called as pipe command. In linux terminal, it is
indicated the symbol |

 Two processes can be joined or communicated with help of the pipe


symbol on the shell terminal

pd[0] pd[0]
Process 1 (P1) Process 2
(P2)
pd[1] pd[1]

 Both processes P1, P2 are executed simultaneously and P1 will pass


data / message to Process P2 as it executes.

Example of Pipe Symbol in Linux Terminal

 Here the output of ls command is given as an input to the wc -l command


using pipe symbol (|).

 Hence, both ls command (Process P1) and wc –l command (Process P2)


can be communicated through pipe symbol (|).

 Using pipe symbol, ‘n’ of processes or commands can be communicated.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 100|Page


I. IPC USING PIPE
PIPE SYSTEM CALL
 In linux c, the pipe system call is created by using the built-in function
called pipe()

Example

int pipe(int pd[2]);

 Here, pipe system call accepts only one argument, which is an integer
array of two pipe descriptors.
 pd[0] is used for reading data / message from the pipe and pd[1] is used
for writing data / message to the pipe.
Pipe (Unnamed Pipe or Anonymous Pipe)
 In linux, if the pipe has no name then it is called as unnamed pipe or
anonymous pipe (gives communication between parent and child
processes)
 It is a communication medium between two or more related or interrelated
processes
 It is mainly used for interprocess communication. It has two ends. They
are:
1. First end is fd[0] which is used for reading mode
2. Second end is fd[1] which is used for writing mode
 It is used for transferring data between two processes / commands /
programs
 It acts like queue data structure. We can write 512 bytes at the same time
but we can read ONLY ONE BYTE at the same time.
 It is an important to note that, pipe is an uni-directional (half duplex or
one-way communication) that is either from left to right or right to left
 It is an important to note that, whatever is written on one end (Ex. write
end) might visible on other end (Ex. read end)

Return Value of Pipe


 It returns 0 if successful otherwise it returns -1
 Return type: int

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 101|Page


Required Header File

#include<unistd.h>

OPERATIONS OF PIPE
 One Way Communication between processes

 One pipe system call is required

 Two Way Communication between processes

 Two pipe system calls are required

 By default, it is a half-duplex method. So the first process will


communicate with second process or second process will
communicate with first process. However, in order to achieve a
full-duplex, another pipe is needed.

BUILT-IN METHODS OF PIPE


1. write(pipe-descriptor[1], void * message, size_t count)
 This method is used to write the string message using the pipe end [1]

 It takes three arguments such as descriptor, message and size

 1st argument is pipe descriptor

 2nd argument is message which is string type

 3rd argument is count which is unsigned int type.

 This method will return the number of bytes written on success case and
will return -1 if the case is failure.

 Return type: ssize_t

2. read(pipe-descriptor[0], void * buffer, size_t count)


 This method is used to read the string message using the pipe end [0]

 It takes three arguments such as descriptor, message and size

 1st argument is pipe descriptor

 2nd argument is message which is string type

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 102|Page


 3rd argument is count which is unsigned int type.

 This method will return the number of bytes read on success case and
will return -1 if the case is failure.

 Return type: ssize_t

3. close(pipe-descriptor)
 This method is used to close the pipe if pipe is already opened

 It takes only one argument which is the integer value of pipe descriptor

 It will return 0 on success case and -1 on failure case.

 Return type: int

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 103|Page


I. SENDING AND RECEIVING STATIC MESSAGES BETWEEN TWO
PROCESSES USING PIPE
(/home/runner/Latest-Shells-21/pipeex1.c)
SOURCE CODE
#include<string.h>
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r;
// pipe descriptors
int p[2];
printf("---------------------------------------------------------\n");
printf("\tSending and Receiving Static Messages-Pipe\n");
printf("---------------------------------------------------------\n");
// Text Messages (fixed messages)
char *sms1="Good Morning\n";
char *sms2="Hello World\n";
unsigned int s=strlen(sms1);
char buf[1024];
// create unnamed pipe using pipe system call
r=pipe(p);
if(r<0)
{
printf("Failed to created unnamed pipe...\n");
exit(1);
}
// send messages to another process
write(p[1],sms1,strlen(sms1));
write(p[1],sms2,strlen(sms1));
printf("Two Messages are sent successfully...(Process 1)\n");

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 104|Page


printf("---------------------------------------------------------\n");
printf("Message from Unnamed Pipe: (Process 2)\n");
// read messages from the pipe (other end) using single buffer
read(p[0],buf,sizeof(buf));
printf("%s",buf);
return 99;
}

OUTPUT

II. FINDING PRIME NUMBER USING PIPE


(Static Input)
(/home/runner/Latest-Shells-21/pipeex3.c)
SOURCE CODE
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
// function returns string as a result
char * findprime(int n)
{
int c=0;
for(int i=0;i<n;i++)
{

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 105|Page


if(n%(i+1)==0)
c++;
}
if(c==2)
return "The Given Number is a prime...\n";
else
return "The Given Number is NOT a prime...\n";
}
// main function
int main()
{
int r,ele;
// pipe descriptors
int p[2];
printf("---------------------------------------------------------\n");
printf("\tFinding Prime Number-Pipe\n");
printf("---------------------------------------------------------\n");
char buf[1024];
// create unnamed pipe using pipe system call
r=pipe(p);
if(r<0)
{
printf("Failed to created unnamed pipe...\n");
exit(1);
}
char *msg="18";
// send single message (string type) to another process (one end)
write(p[1],msg,sizeof(msg));
printf("One Message is sent successfully...(Process 1)\n");
printf("---------------------------------------------------------\n");
printf("Message from Unnamed Pipe: (Process 2)\n");
// read message from pipe (other end)
read(p[0],buf,sizeof(msg));

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 106|Page


printf("Received Data: %s\n",buf);
// convert received string data to integer
int num=atoi(buf);
// pass integer number to function for the prime number detection
char *rs=findprime(num);
// print the result
printf("%s\n",rs);
return 99;
}

IF INPUT IS 18

IF INPUT IS 31

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 107|Page


III. FINDING PRIME NUMBER USING PIPE
(Dynamic Input)
(/home/runner/Latest-Shells-21/pipeex4.c)
SOURCE CODE
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
char * findprime(int n)
{
int c=0;
for(int i=0;i<n;i++)
{
if(n%(i+1)==0)
{
c++;
}
}
if(c==2)
return "The Given Number is a prime...\n";
else
return "The Given Number is NOT a prime...\n";
}
int main()
{
int r;
// array of pipe descriptors for reading and writing
int p[2];
printf("---------------------------------------------------------\n");
printf("\tFinding Prime Number-Pipe\n");
printf("---------------------------------------------------------\n");
char buf[1024];

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 108|Page


// create unnamed pipe using pipe system call
r=pipe(p);
if(r<0)
{
printf("Failed to created unnamed pipe...\n");
exit(1);
}
int ele;
printf("Enter a number: ");
// read a dynamic input which is an integer type
scanf("%d",&ele);
// create a string and allocate a dynamic memory for this type
char *msg=(char *)malloc(sizeof(char *));
// convert integer number to string using sprintf(char*, type, base) method
sprintf(msg,"%d",ele);
// send single message to another process (one end)
write(p[1],msg,sizeof(msg));
printf("One Message is sent successfully...(Process 1)\n");
printf("---------------------------------------------------------\n");
printf("Message from Unnamed Pipe: (Process 2)\n");
// read message from sender using read() method (other end)
read(p[0],buf,sizeof(msg));
printf("Received Data: %s\n",buf);
// convert received string data to integer
int num=atoi(buf);
// pass integer number to function for the prime number detection
char *rs=findprime(num);
// display the results
printf("%s\n",rs);
return 99;
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 109|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 110|Page


IV. SENDING AND RECEIVING DYNAMIC MESSAGES BETWEEN TWO
PROCESSES USING PIPE
(/home/runner/Latest-Shells-21/test2.c)
SOURCE CODE
#include<string.h>
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r,nl;
static int c=0;
// dynamic memory for sender
char *msg=(char *)malloc(sizeof(char *));
// fixed memory for receiver memory (max.memory)
char bf[1024];
// pipe descriptors for reading and writing data
int p[2];
printf("--------------------------------------------------------------------\n");
printf("\tSending & Receiving Dynamic Messages using Pipe\n");
printf("--------------------------------------------------------------------\n");
// create unnamed pipe using pipe system call
r=pipe(p);
if(r<0)
{
printf("Failed to created unnamed pipe...\n");
exit(1);
}
printf("Enter the number of messages to send: ");
scanf("%d",&nl);
printf("Enter the messages:\n");
for(int i=0;i<nl;i++)

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 111|Page


{
printf("Message #%d: \n",(i+1));
scanf("%s",msg);
// write message to process 2
write(p[1],msg,50);
// count the length of the message
s+=strlen(msg);
printf("\tOne SMS is sent\n");
printf("\tSMS Length: %d\n",(int)strlen(msg));
// increment the SMS count by the variable c with 1
c++;
}
printf("%d Messages are Sent Successfully\n",c);
printf("Message from Unnamed Pipe:\n");
printf("Process 2:\n");
printf("---------------------------------------------\n");
for(int i=0;i<nl;i++)
{
read(p[0],bf,50);
printf("%s\n",bf);
}
return 99;
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 112|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 113|Page


V. PARENT AND CHILD PROCESS COMMUNICATION (IPC) USING PIPE
(/home/runner/Latest-Shells-21/ipcpipe.c)
Number of used Pipes : 1
Number of child processes : 1
Number of parent processes : 1
Major system calls used : pipe(), fork()
Types of Pipes : Unnamed Pipe()
Type of Communication : One way
SOURCE CODE
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
int r;
// pipe descriptors for read and write
int p[2];
printf("---------------------------------------------------------\n");
printf("\tIPC-Parent and Child using Pipe (One Way)\n");
printf("---------------------------------------------------------\n");
// variables declarations
char *sms=(char *)malloc(sizeof(char *));
char buf[1024];
// create unnamed pipe using pipe system call
r=pipe(p);
if(r<0)
{
printf("Failed to created unnamed pipe...\n");
exit(1);
}
// call fork() to create parent and child processes
int f=fork();
if(f<0)
{
printf("Error in creating the processes...\n");
exit(0);
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 114|Page


// child process
else if(f==0)
{
printf("Child Process (P1)\n");
printf("Enter the message to send (50 characters maximum): ");
fgets(sms,50,stdin);
// send message from child to parent using pipe
write(p[1],sms,50);
}
// parent process
else It is indicated by keyboard input.
{
wait(NULL);
printf("---------------------------------------------------------\n");
printf("Parent Process (P2)\n");
// receive message from child via pipe
read(p[0],buf,50);
printf("Received Message:\n");
printf("%s\n",buf);
}
return 99;
}

OUTPUT

RESULT
Thus the interprocess communication using pipe has been executed
successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 115|Page


EX.NO: 8 INTERPROCESS COMMUNICATION USING NAMED
PIPE
AIM
To work with interprocess communication using named pipe in linux c
programming.
IPC USING NAMED PIPE (FIFO)
 FIFO stands for First in First Out
 A special kind of the file on the local storage that allows two or more
number of processes to communicate with each other
 Named IPC object which provides communication between two unrelated
processes
 Unlike pipe, it has name (identified by the unique name)
 Unlike pipe, it is a full duplex method which means that first process can
communicate with second process and second process can
communicate with first process.

DIFFERENCE BETWEEN PIPE AND FIFO


S.N FEATURES PIPE (Unnamed Pipe) FIFO (Named Pipe)
1. Description It has no name It has a name (Named
(Unnamed IPC object) IPC object)
2. Creation It is created by the It is created by the
system call pipe() method mkfifo() or
open()
3. Existence It does not exist in the It exists in the file
file systems system
4. Nature By default, it is an It is bidirectional, same
unidirectional FIFO can be used for
reading and writing at
the same time
5. Read & Write Here reader and writer Here, it does not require
operations are done at that both read and write
the same time operations to happen at
the same time.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 116|Page


6. Processes Here data transfer takes It has multiple
place between parent processes
and child process. communicating through
it, like multiple client
server application
7. Communication Here communication is In FIFO, it is not
among the process necessary for the
having related process process having the
related process
(unrelated process)
8. Support Pipe is local to the It is capable of
system and can’t be communicating across
used for the different computers and
communication across network.
the network

NOTE
 Neither pipes nor FIFO allow file positioning. Both reading and writing
operations happen sequentially that is reading from the beginning of the
file and writing at the end of the file.
Required Header File

#include<sys/stat.h> // used for creating FIFO i.e. mkfifo()

CAPACITY OF FIFO
 It has multiple readers or multiple writers
 Bytes from each writer are written automatically up to a maximum size of
PIPE_BUF (4KB on Linux OS)

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 117|Page


BUILT-IN METHODS OF NAMED PIPE (FIFO)
1. mkfifo(const char *pathname, mode_t mode)
 It is used to create a FIFO file
 It takes two arguments. They are
 First argument is pathname of the newly created FIFO file which is
string type (identified by char *)
 Second argument is mode of the FIFO’s permissions.
 Return type: int
2. open(fpath, mode, permission)
 It is used to create a named pipe (FIFO)
 It takes two arguments. First argument is file name and second argument
is mode. The mode can be
 O_CREAT (create mode)
 O_WRONLY (write mode only)
 O_RDONLY (read mode only)
 O_RDWR (read and write support)
 Return type: int
3. write(int file descriptor, void * message, size_t size)
 It is used to write / send the data from one end to another end
 It takes three arguments. They are
1. First argument is the file object
2. Second argument is data / message
3. Third argument is the size of the data
 Return type: ssize_t
4. read(int file descriptor, void * message, size_t size)
 It is used to read / receive the data from named pipe
 It takes three arguments. They are
1. First argument is the file object
2. Second argument is data / message
3. Third argument is the size of the data

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 118|Page


 Return type: ssize_t
5. close(file descriptor)
 It is used to close the file descriptor if it is already opened
 It takes only one argument which is the file descriptor

 Return type: int

I. EXAMPLE OF IPC USING FIFO (NAMED PIPE)


(/home/runner/Latest-Shells-21/fifo1.c)

System Calls : File system calls


Type of Pipe : FIFO (Named Pipe)
Type of Communication : One way

SOURCE CODE
#include <stdio.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include <unistd.h>
// global variables
char m1[]="Hello World.";
char m2[]="Good Morning.";
char m3[]="Welcome to Chennai.\n";
void sendMessage()
{
int fd;
// create new file (FIFO) for create and write mode with necessary permission
fd=open("sms.txt",O_CREAT| O_WRONLY,0777);
// write the three messages to named pipe
write(fd,m1,strlen(m1));

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 119|Page


write(fd,m2,strlen(m2));
write(fd,m3,strlen(m3));
printf("Three Messages are successfully sent to named pipe...\n") ;
// close the file descriptor
close(fd);
}
void receiveMessage() It is better to use length of sender’s
message in receiver side
{
int fp;
char buf1[100],buf2[100],buf3[100];
// open same file (FIFO) for read mode
fp=open("sms.txt",O_RDONLY);
// read three messages from named pipe
read(fp,buf1,strlen(m1));
read(fp,buf2,strlen(m2));
read(fp,buf3,strlen(m3));
printf("Messages from FIFO:\n");
printf("------------------------------------------------------\n");
printf("\t%s\n",buf1);
printf("\t%s\n",buf2);
printf("\t%s\n",buf3);
Same FIFO file can be used for
// close the file descriptor
reading mode.
close(fp);
}

int main()
{
printf("------------------------------------------------------\n");
printf("\t\tIPC using FIFO (Named Pipe)\n");
printf("------------------------------------------------------\n");
sendMessage();

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 120|Page


receiveMessage();
return 99;
}
OUTPUT

RESULT
Thus the interprocess communication using named pipe has been
executed successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 121|Page


EX.NO: 9 MULTITHREADING USING PYTHON

AIM
To practice the multithreading programming using python language.
THREADING
 Thread is a path of the execution within a process.

TASK BASED TYPES


1. Single Threading

2. Multithreading

DIFFERENCE BETWEEN SINGLE THREAD AND MULTIPLE THREADS


S.N SINGLE THREAD MULTITHREADING
1. Performs single task Performs multitasking. Doing more
than one job at the same time
2. It consists of only one thread It consists of several threads
3. It is used for experimental It is used for larger tasks
purpose

LIFE CYCLE OF THREADS


 Thread has five life cycles. It is always live in any of the state.

1. New born state (New state)

2. Runnable state

3. Running state (execution state)

4. Blocked state

5. Dead state (End state)

BUILT-IN METHODS
1. start()
 This is runnable state (waiting for the execution)
 This is method is used to start the thread

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 122|Page


 Return type : nothing
2. threading.currentThread().getName()
 This method is used to display the name of currently executing or
running thread
 Return type : String
Thread Creation
 Thread is created by using the super class Thread

Thread(name=<user-defined-name, target=<function-name>, )
 It is a built-in class which is used to create a new thread object

 It takes two or more arguments

 First argument is name of thread. It can be any name set by the user. It
is optional argument

 Second argument is target which is used to call the user defined


function

Required Module

threading

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 123|Page


I. EXAMPLE OF SINGLE THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3

SOURCE CODE
from threading import *
# user defined function
def welcome():
print("Hello World...")
print("------------------------------------------") Newborn state
print("\tSingle Thread")
print("------------------------------------------")
# creating object for single thread Runnable state

t1=Thread(target=welcome, name="Thread 1")


# start the thread by calling start method
t1.start()

OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 124|Page


Pictorial Diagram

Current Thread (Main Thread)

Sub Thread
t1

MULTITHREADING
 Process of executing more than one thread at the same time (Execution
of multiple threads simultaneously)
 It is an important to note that, we can’t predict which thread will run first.
 By all the threads will be running in parallel at the same time.
 It is an important to note that, the main or current thread can randomly
start any thread from the list of threads.

II. EXAMPLE OF MULTITHREADING


(Asynchronous Processes)
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3

SOURCE CODE
from threading import *
# user defined function 1
def m1():
for i in range(3):
print("Good Morning...")
# user defined function 2
def m2():

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 125|Page


for i in range(3):
print("Good Evening...")
# user defined function 3
def m3():
for i in range(3):
print("Good Night...")
print("------------------------------------------")
print("\tMultithreading")
print("------------------------------------------")
# creating objects for multiple threads
t1=Thread(target=m1,name="Morning")
t2=Thread(target=m2,name="Evening")
t3=Thread(target=m3,name="Night")
# start the threads by calling start method
t1.start()
t2.start()
t3.start()

Pictorial Diagram

Current Thread (Main Thread)

Sub Thread Sub Thread Sub Thread


t1 t2 t3

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 126|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 127|Page


III. EXAMPLE OF MULTITHREADING
(Synchronous Processes using join() method)
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3
Existing Issues
 By default, the threads are running parallel in multithreading
 In the execution of multithreading using asynchronous methods, the
threads will be running in parallel. That’s why the output came
differently in the previous example.
 So in order to execute thread one by one (sequential order) during the
multithreading, the join method will be used.

SOURCE CODE
from threading import *
# user defined function 1
def m1():
for i in range(3):
print("Good Morning...")
# user defined function 2
def m2():
for i in range(3):
print("Good Evening...")

# user defined function 3


def m3():
for i in range(3):
print("Good Night...")
print("------------------------------------------")
print("\tMultithreading")
print("------------------------------------------")

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 128|Page


# creating objects for multiple threads
t1=Thread(target=m1,name="Morning")
t2=Thread(target=m2,name="Evening")
t3=Thread(target=m3,name="Night")
# start thread 1
t1.start()
# wait until thread 1 is finished (main and sub threads t2, t3 should wait)
t1.join()
# start thread 2 after thread 1
t2.start()
# wait until thread 2 is finished (main and sub threads t1, t3 should wait)
t2.join()
# start thread 3 after thread 2
t3.start()
# wait until thread 3 is finished (main and sub threads t1, t2 should wait)
t3.join()
# end of the main thread
print("End of the main thread...")

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 129|Page


OUTPUT

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 130|Page


IV. DETECTION OF CURRENTLY EXECUTING THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3

SOURCE CODE
from threading import *
import threading
# user defined function 1
def m1():
tname=threading.currentThread().getName()
print("Current Thread\t: ",tname)
print("Good Morning...")
# user defined function 2
def m2():
tname=threading.currentThread().getName()
print("Current Thread\t: ",tname)
print("Good Evening...")
# user defined function 3
def m3():
tname=threading.currentThread().getName()
print("Current Thread\t: ",tname)
print("Good Night...")
# main thread
print("-----------------------------------------------------------")
print("\tFinding Current Thread - Multithreading")
print("-----------------------------------------------------------")
# creating objects for multiple threads
t1=Thread(target=m1,name="Morning")
t2=Thread(target=m2,name="Evening")
t3=Thread(target=m3,name="Night")

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 131|Page


# start threads
t1.start()
t2.start()
t3.start()
# end of the main thread
print("End of the main thread...")

OUTPUT

GENERAL TYPES OF THREAD


 Like java, python supports two types of threads. They are

1. Daemon thread
2. Non daemon thread (User Thread)
1. Daemon Thread
 If a thread is running in background mode, then it is called as daemon
thread
 It has low priority level than user thread
 This is created by adding the boolean value to the daemon argument of
the Thread class.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 132|Page


2. Non Daemon Thread
 If a thread is running in foreground mode, then it is called as non
daemon thread (user thread)
 It has high priority level than daemon thread
 This is created by the thread class.

DIFFERENCE BETWEEN DAEMON THREAD AND NON DAEMON


THREAD
S.N DAEMON THREAD NON DAEMON THREAD
1. It is always runs in It is always runs in foreground mode
background mode
2. Main program does not wait Here main program waits for user
for daemon thread to finish threads have to terminate
its task
3. It has low priority It has high priority
4. It is not used for important Any important task is done by the user
task. It is generally used for thread.
some background tasks
which are not important
5. It is created by the Python It is created by the application or
Virtual Machine (PVM) program.
6. If all the threads are finished PVM won’t force the user threads for
their execution, the PVM will termination. So it waits for user threads
force the daemon threads to to terminate themselves.
finish their execution.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 133|Page


I. EXAMPLE OF DAEMON THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3

SOURCE CODE
from threading import *
from time import sleep
# user defined function 1
def m1():
for i in range(3):
print("Good Morning...")
sleep(2)
# user defined function 2
def m2():
for i in range(3):
print("Good Evening...")
# user defined function 3 Convert user thread to non-
def m3(): daemon thread.

for i in range(3):
print("Good Night...")
print("------------------------------------------------")
print("\tDaemon Thread")
print("------------------------------------------------")
# creating objects for multiple threads
# convert thread t1 to daemon thread by setting the boolean true to the
daemon argument of thread class
t1=Thread(target=m1,name="Morning", daemon=True)
# non daemon threads
t2=Thread(target=m2,name="Evening")
t3=Thread(target=m3,name="Night")

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 134|Page


# start the thread by calling start method
t1.start()
t2.start()
t3.start()

OUTPUT

NOTE
 In the above output screenshot, the daemon thread t1  Good Morning
is still running in the background mode.
 Eventhough all threads (including main thread) are terminated, the
daemon thread is still aliving and running in the background.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 135|Page


II. EXAMPLE OF NON DAEMON THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3

SOURCE CODE
from threading import *
from time import sleep
# user defined function 1
def m1():
for i in range(3):
print("Good Morning...")
sleep(2)
# user defined function 2
def m2():
for i in range(3):
print("Good Evening...")
# user defined function 3
def m3():
for i in range(3):
print("Good Night...")
print("----------------------------------------------------------")
print("\tNon Daemon Thread(User Threads)")
print("----------------------------------------------------------")
# creating objects for multiple threads
# Non Daemon Threads
t1=Thread(target=m1,name="Morning")
t2=Thread(target=m2,name="Evening")
t3=Thread(target=m3,name="Night")
# start the threads by calling start method
t1.start()

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 136|Page


t2.start()
t3.start()

OUTPUT

In the previous example, main thread and user threads


are terminated. But still daemon thread t1 Good
Morning is running in background jobs.

Here, main thread and user threads are terminated. No


threads are running in background.

RESULT
Thus the multithreading programming using python has been executed
successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 137|Page


EX.NO: 10 FILE ALLOCATION STRATEGIES

AIM
To practice the file allocation strategy in linux programming.
FILE ALLOCATION METHODS
 It defines, how the files are stored in the disk blocks.

 It supports three methods. They are

1. Sequential File Allocation (Contiguous Allocation)

2. Indexed File Allocation

3. Linked File Allocation

BENEFITS
 Efficient disk space utilization

 Fast access to the file blocks

1. SEQUENTIAL FILE ALLOCATION (CONTIGUOUS ALLOCATION)


 Process of allocating resources to the contiguous blocks are called as
sequential file allocation

 Both sequential and direct accesses are supported by this method.

 The directory entry for a file with contiguous allocation contains

 Address of starting block

 Length of the allocated portion.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 138|Page


Example 1

Example 2

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 139|Page


I. EXAMPLE OF SEQUENTIAL ALLOCATION METHOD
SOURCE CODE
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BLOCKSIZE 50
int b[BLOCKSIZE+1];
int number,length;
void seq_fileallocation()
{
printf("Enter the block number: ");
scanf("%d",&number);
// check for invalid number
if(number>BLOCKSIZE)
{
printf("Invalid Block Number.\nPlease Enter the block number in the
range between 1 to 50\n");
}
else
{
// check the slot is free or not
if(b[number]==0)
{
printf("Enter the number of lengths for the block %d: ", number);
scanf("%d",&length);
int c=0;
// increment the counter for the blocks which are given by the user
for(int i=number;i<number+length;i++)
{
if(b[i]==0)
{

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 140|Page


c++;
}
}
// if counter equals to exact length, then slot should be free
if(c==length)
{
// allocate file / block for the user request
for(int i=number;i<number+length;i++)
{
b[i]=1;
printf("block %d is allocated ...\n",i);
}
printf("File is allocated successfully for the block %d\n",number);
}
else if((number+length)>BLOCKSIZE)
{
printf("File lengths are too out of range than MAX Capacity of Block
%d...\n",BLOCKSIZE);
}
else
{
printf("File lengths are not free for the given block\n");
}
}
else
{
printf("File / Block is already Allocated\nPlease try some block
%d\n",number);
}
}
}
// print the contents of table

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 141|Page


void disp()
{
for(int i=1;i<BLOCKSIZE+1;i++)
{
printf(" %d",b[i]);
if(i%8==0)
printf("\n");
}
printf("\n");
}
int main()
{
// allot the inputs for the blocks
for(int i=1;i<BLOCKSIZE+1;i++)
{
b[i]=0;
}
printf("Initial Block Table\n");
disp();
char ch[150];
while(5)
{
printf("---------------------------------------\n");
printf("\tSequential File Allocation\n");
printf("---------------------------------------\n");
printf("Before File Allocation, Table Contents:\n");
disp();
seq_fileallocation();
printf("After File Allocation, Table Contents:\n");
disp();
printf("Do you want to continue: Press Yes / No : ");

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 142|Page


scanf("%s",ch);
if(strcmp(ch, "yes")==0||strcmp(ch, "Yes")==0||strcmp(ch, "YES")==0)
continue;
else
exit(1);
}
}

Allocation for Block Number 12 and its Lengths 5

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 143|Page


Allocation for Block Number 3 and its Lengths 7 after that checking
block number 9

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 144|Page


Allocation for Block Number 49 and its Lengths 5

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 145|Page


Allocation for Block Number 49 and its Lengths 5 (-Continue) after that
checking block number 50

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 146|Page


2. INDEXED AL FILE ALLOCATION
 Unlike sequential file allocation, this method uses an additional block
called as the index block which is used to store all the disk pointers

 For each file, there is an individual index block.

 In the index block, the ith entry holds the disk address of the ith file
block.

 It is an important to note that, indexed block does not hold the file data,
but it holds the pointers to all the disk blocks allotted to the particular file.

 The directory entry contains the address of the index block as shown in
the below image:

PICTORIAL REPRESENTATION
Directory Entry

File Index Block


bus 11

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 147|Page


II. EXAMPLE OF INDEXED ALLOCATION METHOD
SOURCE CODE
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BLOCKSIZE 50
int b[BLOCKSIZE+1], ib[BLOCKSIZE+1];
int number,length;
void indexed_allocation()
{
printf("Enter the index block number: ");
scanf("%d",&number);
// check for invalid number
if(number>BLOCKSIZE)
{
printf("Invalid index Block Number.\nPlease Enter the index block number
in the range between 1 to 50\n");
}
else
{
// check the slot is free or not
if(b[number]==0)
{
printf("Enter the number of files for the block %d: ", number);
scanf("%d",&length);
printf("Enter the blocks:\n");
for(int i=0;i<length;i++)
{
printf("Files #%d: ",(i+1));
scanf("%d", &ib[i]);
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 148|Page


int c=0;
// increment the counter for the blocks which are given by the user
for(int i=0;i<length;i++)
{
if(b[ib[i]]>BLOCKSIZE)
{
printf("Index Block is Out of Range.\nPlease enter the blocks in
the range between 1-50\n");
break;
}
else if(b[ib[i]]==0)
{
c++;
}

}
// if counter equals to exact length, then slot should be free
if(c==length)
{
// allocate file / block for the user request
for(int i=0;i<length;i++)
{
b[ib[i]]=1;
printf("Index block %d is allocated ...\n",ib[i]);
}
printf("File is allocated successfully for the block %d\n",number);
}
// if the submitted index block is greater than MAXIMUM give message
else
{
printf("File lengths are not free for the given block\n");
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 149|Page


}
else
{
printf("File / Block is already Allocated\nPlease try some block");
}
}
}
// print the contents of table
void disp()
{
for(int i=1;i<BLOCKSIZE+1;i++)
{
printf(" %d",b[i]);
if(i%8==0)
printf("\n");
}
printf("\n");
}
int main()
{
// allot the inputs for the blocks
for(int i=1;i<BLOCKSIZE+1;i++)
{
b[i]=0;
}
printf("Initial Block Table\n");
disp();
char ch[150];
while(5)
{
printf("---------------------------------------\n");

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 150|Page


printf("\tIndexed File Allocation\n");
printf("---------------------------------------\n");
printf("Before File Allocation, Table Contents:\n");
disp();
indexed_allocation();
printf("After File Allocation, Table Contents:\n");
disp();
printf("Do you want to continue: Press Yes / No : ");
scanf("%s",ch);
if(strcmp(ch, "yes")==0||strcmp(ch, "Yes")==0||strcmp(ch, "YES")==0)
continue;
else
exit(1);
}
}

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 151|Page


ALLOCATION OF INDEX BLOCK 5

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 152|Page


ALLOCATION OF INDEX BLOCK 5 – (Continue)

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 153|Page


ALLOCATION OF INDEX BLOCK 35

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 154|Page


CHECKING ALREADY ALLOCATED INDEX BLOCKS FOR 32, 50

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 155|Page


CHECKING INVALID INDEX NUMBER 59

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 156|Page


CHECKING ALREADY ALLOCATED INDEX NUMBERS 14, 25

RESULT
Thus the file allocation strategies like sequential and indexed file
allocation methods have been executed successfully.

IT7411 – OS LABORATORY (4/8 B.TECH – IT) 157|Page

You might also like