[go: up one dir, main page]

0% found this document useful (0 votes)
337 views269 pages

OS by JJsir

Uploaded by

trushalkjk9227
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
337 views269 pages

OS by JJsir

Uploaded by

trushalkjk9227
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 269

OS by JJsir

SHREE H. J. DOSHI INFORMATION TECHNOLOGY INSTITUTE JAMNAGAR

OPERATING SYSTEMS
CONCEPTS WITH UNIX / LINUX
BY JJ SIR

CH-1 : INTRODUCTION, PROCESS AND THREAD, PROCESS SCHEDULING


OS by JJsir

What is OS?

 OS is an collections of softwares which manges hardware


resource to provide services to run your computer applications

 Operating System is a software, which makes a computer to


actually work.

 It is the software the enables all the programs we use.


 The OS organizes and controls the hardware.

 OS acts as an interface between the application programs and


the machine hardware.

 Examples: Windows, Linux, Unix and Mac OS, etc.,


OS by JJsir

What OS does?

An operating system performs basic tasks such as,

 controlling and allocating memory,


 prioritizing system requests,
 controlling input and output devices,
 facilitating networking and
 managing file systems.
OS by JJsir

Structure of Operating System

Application Programs

System Programs

Software (Operating System)

HARDWARE

(Contd…)
OS by JJsir

Structure of Operating System

 The structure of OS consists of 4 layers:


1. Hardware
 Hardware consists of CPU, Main memory, I/O Devices, etc,

2. Software (Operating System)


 Software includes process management routines, memory
management routines, I/O control routines, file management
routines.

(Contd…)
OS by JJsir

Structure of Operating System

3. System programs
 This layer consists of compilers, Assemblers, linker etc.

4. Application programs
 This is dependent on users need. Ex. Railway reservation
system, Bank database management etc.,
OS by JJsir

Functions of the Operating System

 Resource Management: The operating system manages and allocates memory,


CPU time, and other hardware resources among the various programs and
processes running on the computer.
 Process Management: The operating system is responsible for starting, stopping,
and managing processes and programs. It also controls the scheduling of
processes and allocates resources to them.
 Memory Management: The operating system manages the computer’s primary
memory and provides mechanisms for optimizing memory usage.
 Security: The operating system provides a secure environment for the user,
applications, and data by implementing security policies and mechanisms such as
access controls and encryption.
 Job Accounting: It keeps track of time and resources used by various jobs or
users.
OS by JJsir

Functions of the Operating System

 File Management: The operating system is responsible for organizing and managing
the file system, including the creation, deletion, and manipulation of files and
directories.
 Device Management: The operating system manages input/output devices such as
printers, keyboards, mice, and displays. It provides the necessary drivers and
interfaces to enable communication between the devices and the computer.
 Networking: The operating system provides networking capabilities such as
establishing and managing network connections, handling network protocols, and
sharing resources such as printers and files over a network.
 User Interface: The operating system provides a user interface that enables users to
interact with the computer system. This can be a Graphical User Interface (GUI), a
Command-Line Interface (CLI), or a combination of both.
 Backup and Recovery: The operating system provides mechanisms for backing up
data and recovering it in case of system failures, errors, or disasters.
OS by JJsir

Features of OS

 Convenient to use: One of the objectives is to make the computer system


more convenient to use in an efficient manner.
 User Friendly: To make the computer system more interactive with a more
convenient interface for the users.
 Easy Access: To provide easy access to users for using resources by acting
as an intermediary between the hardware and its users.
 Management of Resources: For managing the resources of a computer in
a better and faster way.
 Controls and Monitoring: By keeping track of who is using which resource,
granting resource requests, and mediating conflicting requests from
different programs and users.
 Fair Sharing of Resources: Providing efficient and fair sharing of resources
between the users and programs.
OS by JJsir

Batch processing

 History of batch
 The earliest computers were extremely expensive devices, and very slow. Machines
were typically dedicated to a particular set of tasks and operated by control panel,
the operator manually entering small programs via switches in order to load and run
other programs. These programs might take hours, even weeks, to run. As computers
grew in speed, run times dropped, and suddenly the time taken to start up the next
program became a concern. The batch processing methodologies evolved to
decrease these dead times, queuing up programs so that as soon as one completed,
the next would start.
 In Batch processing same type of jobs batch (BATCH- a set of jobs with similar needs)
together and execute at a time.
 The OS was simple, its major task was to transfer control from one job to the next.
 The job was submitted to the computer operator in form of punch cards. At some
later time the output appeared.
 The OS was always resident in memory.
 Common Input devices were card readers and tape drives.
OS by JJsir

Batch processing
OS by JJsir

Batch processing

 Advantages
 After input process is over, while processing is going on user can attend
other jobs.
 It allows sharing of computer resources among many user and programs
 It shifts time of job processing to when the computing resources are less
busy
 Disadvantages
 Difficult to provide priority scheduling
 Access to one program is not possible
 If result of particular program or time detail are required, you have to
wait till entire batch is processed
OS by JJsir

Multiprogramming

 OS which handles more than one program in main memory at a


time is known as multiprogramming OS

 In Multiprogramming, number of processes reside in main


memory at a time.

 The main advantage of this OS is CPU can allocate time to


several programs

 If any I/O wait happened in a process, then CPU switches from


that job to another job.

 Hence CPU in not idle at any time.


OS by JJsir

Multiprogramming

• Figure describe of multiprogramming OS


system.
• The main memory consists of 5 jobs Job 1
at a time, the CPU executes one by
one.
Job 2

Job 3

Job 4
OS by JJsir

Multiprogramming

 Advantages:
 Time is not wasted in switching from one program to another
 Many programs run at same time
 Important and small jobs need not wait for batch

 Disadvantages :-
 OS is complicated because many programs are handle together

 Jobs of resource management and memory management


increases
 Large main memory required
OS by JJsir

Time Sharing Systems

 In this, the CPU time is shared by different processes, so it is


called as “Time sharing Systems”.

 The time sharing OS keeps only few programs in main


memory and rest of the program stored on disk storage

 A short period of time during which user can get attention


of CPU is known as time slice or time slot

 In this OS, only one program can be in the control of CPU


at a given time like Multiprogramming OS
OS by JJsir

Time Sharing Systems

 It is not possible to keep program of all user


simultaneously in main memory because of limited
main memory
 Main features of Time Sharing OS are as follows :
 Processing time are divided into
various program called time slice
 Each program is given the CPU

time one by one


OS by JJsir

Time Sharing Systems

 Advantages of TSOS
 Allprograms get equal attention and small program get
over fast
 Reduce CPU idle time

 Computing cost is very less

 Disadvantages of TSOS
 OS is more complicated

 To use other programs which is not in main memory of


TSOS user have to wait till it load
OS by JJsir

Real-time Operating System

 A system in which a transaction access and updates a


file quickly enough to affect the original decision-
making is called Real time system

 This OS is used where immediate response from


computer requires. Eg.-Stock market

 The important feature is to get immediate and direct


access to record
OS by JJsir

Real-time Operating System

 Advantages of RTOS :-
 Accessand retrieval of record is quick
 Response time is very less

 Data processing is very fast

 Disadvantages of RTOS :-
 Veryexpensive
 Question of security

 Applications
 Stock market
 Airline reservation system
OS by JJsir

Best hacking Operating System

 Kali Linux
 BlackBox
 Parrot Security Operating System
 Fedora Security Lab
 DEFT Linux
 Live Hacking Operating System
 Network Security Toolkit (NST)
 BlackArch Linux
 Cyborg Hawk Linux
 NodeZero
OS by JJsir

OS Types (User Point of View)

 The goal of the Operating System is to maximize the work and


minimize the effort of the user.
 Most of the systems are designed to be operated by single user,
however in some systems multiple users can share resources, memory. In
these cases, Operating System is designed to handle available
resources among multiple users and CPU efficiently.
 Operating System must be designed by taking both usability and
efficient resource utilization into view.
 In embedded systems (Automated systems) user view is not present.
 Operating System gives an effect to the user as if the processor is
dealing only with the current task, but in background processor is
dealing with several processes.
OS by JJsir

OS Types (Features Point of View)

 From the system point of view Operating System is a program


involved with the hardware.
 Operating System is allocator, which allocate memory,
resources among various processes. It controls the sharing of
resources among programs.
 It prevents improper usage, error, and handle deadlock
conditions.
 It is a program that runs all the time in the system in the form
of Kernel.
 It controls application programs that are not part of Kernel.
OS by JJsir

What is process?

 Process is nothing its program in execution.


 Execution of user program in Multiprogramming or
Time sharing system is represented by set of process
 Process is made up of tuple
 A tuple space is an tool of the common memory for
arrange computing
 Tuple consist of process id, code, data, register
value and PC value.
OS by JJsir

Process

 Process id is unique id which assign of process


 Code is a program code
 Data is data used during its execution
 Register value is value in which machine register
 PC value is address in program where to execute
 At the moment only one process is actively executing
which is given to CPU
 Process is sequential in nature it means instruction in
program code is executed one after another
OS by JJsir

Process State

 A state is a unique configuration of information in a


program or machine.
 In most of these states, processes are "stored" on main
memory
 Each process may be in one of the following states
OS by JJsir

Process State

 New or create :-
 The process has been created
 This is done when user types a name of a program to be executed
 Ready or waiting :-
 A "ready" or "waiting" process has been loaded into main
memory and is awaiting execution on a CPU There may be many
"ready" processes at any one point of the systems execution - for
example, in a one processor system, only one process can be
executing at any one time, and all other "concurrently executing"
processes will be waiting for execution.
 Running :-
 A process is an running state, if it has given all resources needed
for its execution
OS by JJsir

Process State

 Blocked :-
 The process is waiting some events to occur
 Terminated :-
A process may be terminated, either from the "running"
state by completing its execution or by explicitly being
killed
OS by JJsir

Process State transitions

The working of Process is explained in following steps:


 User-running: Process is in user-running.
 Kernel-running: Process is allocated to kernel and hence, is in kernel mode.
 Ready to run in memory: Further, after processing in main memory process is
rescheduled to the Kernel.i.e.The process is not executing but is ready to run as soon
as the kernel schedules it.
 Asleep in memory: Process is sleeping but resides in main memory. It is waiting for
the task to begin.
 Ready to run, swapped: Process is ready to run and be swapped by the processor
into main memory, thereby allowing kernel to schedule it for execution.
 Sleep, Swapped: Process is in sleep state in secondary memory, making space for
execution of other processes in main memory. It may resume once the task is fulfilled.
 Pre-empted: Kernel preempts an on-going process for allocation of another process,
while the first process is moving from kernel to user mode.
 Created: Process is newly created but not running. This is the start state for all
processes.
OS by JJsir

Process Control Block (PCB)

 Process Control Block is a data structure that contains


information of the process related to it.
 The process control block is also known as a task control
block, entry of the process table, etc.
 It is very important for process management as the
data structuring for processes is done in terms of the
PCB.
 It also defines the current state of the operating
system.
OS by JJsir

Structure of the Process Control Block

 The process control


stores many data items
that are needed for
efficient process
management. Some of
these data items are
explained with the help
of the given diagram
OS by JJsir

Process Control Block (PCB)

 Process State
 Thisspecifies the process state i.e. new, ready, running,
waiting or terminated.
 Process Number
 This shows the number of the particular process.
 Program Counter
 This
contains the address of the next instruction that
needs to be executed in the process.
OS by JJsir

Process Control Block (PCB)

 Registers
 Thisspecifies the registers that are used by the process.
They may include accumulators, index registers, stack
pointers, general purpose registers etc.
 List of Open Files
 These are the different files that are associated with
the process
OS by JJsir

Process Control Block (PCB)

 CPU Scheduling Information


 The process priority, pointers to scheduling queues etc. is the CPU
scheduling information that is contained in the PCB.
 Memory Management Information
 The memory management information includes the page tables or the
segment tables depending on the memory system used.
 I/O Status Information
 This information includes the list of I/O devices used by the process,
the list of files etc
OS by JJsir

Context switching

 An operating system is a program loaded into a system or


computer. and manage all the other program which is running
on that OS Program, it manages the all other application
programs.
 In other words, we can say that the OS is an interface between
the user and computer hardware.
 The three different categories of context-switching are as follows.
 Interrupts
 Multitasking
 User/Kernel switch
OS by JJsir

Context switching

 Interrupts: When a CPU requests that data be read from a


disc, if any interruptions occur, context switching automatically
switches to a component of the hardware that can handle the
interruptions more quickly.
 Multitasking: The ability for a process to be switched from the
CPU so that another process can run is known as context
switching. When a process is switched, the previous state is
retained so that the process can continue running at the same
spot in the system.
 Kernel/User Switch: This trigger is used when the OS needed
to switch between the user mode and kernel mode.
OS by JJsir

Threads

 A thread is a single sequence stream within a process. Threads are also called
lightweight processes as they possess some of the properties of processes.
 Each thread belongs to exactly one process. In an operating system that
supports multithreading, the process can consist of many threads.
 But threads can be effective only if CPU is more than 1 otherwise two threads
have to context switch for that single CPU.
 A thread shares with its peer threads few information like code segment, data
segment and open files. When one thread alters a code segment memory item,
all other threads see that.
 Multi-threading
 Multithreading is a technique used in operating systems to improve the performance and
responsiveness of computer systems. Multithreading allows multiple threads (i.e., lightweight
processes) to share the same resources of a single process, such as the CPU, memory, and
I/O devices.
OS by JJsir

Benefits of threads

 Responsiveness: If the process is divided into multiple threads, if one thread completes
its execution, then its output can be immediately returned.
 Faster context switch: Context switch time between threads is lower compared to the
process context switch. Process context switching requires more overhead from the CPU.
 Effective utilization of multiprocessor system: If we have multiple threads in a single
process, then we can schedule multiple threads on multiple processors. This will make
process execution faster.
 Resource sharing: Resources like code, data, and files can be shared among all threads
within a process. Note: Stacks and registers can’t be shared among the threads. Each
thread has its own stack and registers.
 Communication: Communication between multiple threads is easier, as the threads
share a common address space. while in the process we have to follow some specific
communication techniques for communication between the two processes.
 Enhanced throughput of the system: If a process is divided into multiple threads, and
each thread function is considered as one job, then the number of jobs completed per
unit of time is increased, thus increasing the throughput of the system.
OS by JJsir

Types of threads

 1. User-level thread.
 2. Kernel level thread.

 User Level Threads


 User Level Thread is a type of thread that is not created using system calls. The kernel
has no work in the management of user-level threads. User-level threads can be easily
implemented by the user.

 Kernel Level Threads


 A kernel Level Thread is a type of thread that can recognize the Operating system
easily. Kernel Level Threads has its own thread table where it keeps track of the system.
The operating System Kernel helps in managing threads.
OS by JJsir

Difference between Process V/s Thread

Process Thread
Process means any program is in execution. Thread means a segment of a process.

The process takes more time to terminate. The thread takes less time to terminate.

It takes more time for creation. It takes less time for creation.

It also takes more time for context switching. It takes less time for context switching.

The process is less efficient in terms of Thread is more efficient in terms of


communication. communication.

We don’t need multi programs in action for


Multiprogramming holds the concepts of multi-
multiple threads because a single process
process.
consists of multiple threads.

The process is isolated. Threads share memory.


OS by JJsir

Process Scheduling

 Process scheduling is a technique that is used when there are limited resources and
many processes are take part for execution;

 If the system has more than one processor, then it is possible to execute more than
one process at the same time.

 In a single processor system, only one process can be executed at any given time.

 If there are more processes, then the operating system must schedule the processes.

 It means that some processes will be executed and others will have to wait.

 There are many strategies for deciding which process should be assigned to the
CPU.
OS by JJsir

Process Scheduling

 Scheduling Queues

 Below is a list of the most common types of queues and their purpose.

 Job Queue - Each entering process goes into job queue. Processes in
job queue reside on mass storage and awaits the allocation of main
memory.

 Ready Queue - The set of all processes that are in main memory and
are waiting for CPU time, are kept in ready queue.

 Waiting (Device) Queues - The set of processes waiting for allocation


of certain I/O devices, are kept in waiting device queue.
OS by JJsir

Types Of Scheduling

 Preemptive Scheduling :-
 Preemptive is when a new process arrives, its burst time is
compared with time of currently executing process and if
a new process is having a shortest burst time then new
process is given the CPU time

 Non Preemptive Scheduling :-


 Non preemptive is when a process arrives if at all the
arrived process has shortest burst time then also the
current process is first executed
OS by JJsir

CPU scheduling algorithms

 FCFS
 SJN
 Round Robin
 Priority Base Non Preemptive
 Priority Base Preemptive
OS by JJsir

FCFS (First Come First Serve)

 FCFS is simplest CPU scheduling in system


 In this scheduling which process come first is given
service first by CPU
 Main important feature of FCFS is scheduling is
process executed sequential without any priority
 consider the following set of process that arrived at
time zero, with length of CPU burst time given in
millisecond
 Burst time is nothing it’s the time required to
complete the particular process.
OS by JJsir

FCFS (First Come First Serve)

Process Burst time


P1 24
P2 03
P3 03
If process arrives in order P1,P2 and P3 & served in FCFS
than the waiting time for particular job is
24/3+3/3+3/3
10ms
So the average waiting time is 10ms in FCFS
OS by JJsir

SJF (Shortest Job First/Next)

 SJF scheduling associated with length of each


process.
 When CPU is available it is assign to the process
that has smallest CPU burst time.
 If two processes have same burst length then FCFS
scheduling is used
OS by JJsir

SJF (Shortest Job First/Next)

Process Burst time


P1 07
P2 04
P3 03
 If process arrives in order P1,P2 and P3 & served in
SJF then process which require short time execute first
then next
 The SJF scheduler is exactly like FCFS except that
instead of choosing the job at the front of the queue, it
will always choose the shortest job available
 SJF scheduling is either preemptive or non preemptive
OS by JJsir

Round Robin Scheduling

 This is one of the oldest, simplest and widely used scheduling


 This scheduling is specially designed for Time Sharing
Operating System
 It consist of small unit of time is called quantum or time slice
 A time slice generally from 10 to 100ms
 In this every process has given time slice for execution
 Round Robin is preemptive. In other word it does not wait for a
process or give up control
OS by JJsir

Round Robin Scheduling

ms P1 P2 P3 P4 P5
 In this CPU picks up 1st process from ready
queue, 0 ms 9 4 5 7 3

3 ms 6 4 5 7 3
 set the timer and dispatch the process
6 ms 6 1 5 7 3
 E.g.-if process and quantum time q = 3 then
9 ms 6 1 2 7 3

Process Burst Time(ms) 12 ms 6 1 2 4 3

P1 9 15 ms 6 1 2 4 0

18 ms 3 1 2 4 X
P2 4
19 ms 3 0 2 4 X
P3 5
21 ms 3 X 0 4 X
P4 7
24 ms 3 X X 1 X
P5 3 27 ms 0 X X 1 X

TOTAL 28 28 ms X X X 0 X

P1 P2 P3 P4 P5 P1 P2 P3 P4 P1 P4
3 6 9 12 15 18 19 21 24 27 28
OS by JJsir

Round Robin Scheduling

 Waiting time = total waiting time – No. of MS the process already


executed
 Waiting time for process :-
 P1 = 24 – 6 = 18 ms
 P2 = 18 – 3 = 15 ms
 P3 = 19 – 3 = 16 ms
 P4 = 27 – 6 = 21 ms
 P5 = 12 – 0 = 12 ms
 Total waiting time = 82 ms
 Average waiting time = 82/5 = 16.4 ms
 P1 = 27 ms
 P2 = 19 ms
 P3 = 21 ms
 P4 = 28 ms
 P5 = 15 ms

 Total time = 110 ms


 Average time = 110/5 = 22 ms
OS by JJsir

Priority Base Non Preemptive V/s Priority Base Preemptive

PRIORITY PREEMPTIVE SCHEDULING PRIORITY NON PREEMPTIVE SCHEDULING


If a process with higher priority than the Once resources are allocated to a process,
process currently being executed arrives, the the process holds it till it completes its burst
CPU is preempted and given to the higher time even if a process with higher priority is
priority process. added to the queue.
Preemptive scheduling is more flexible. Non-preemptive scheduling is rigid.
The waiting time for the process having the The waiting time for the process having the
highest priority will always be zero. highest priority may not be zero.
It is more expensive and difficult to
It is cheaper to implement and faster as less
implement. Also a lot of time is wasted in
switching is required.
switching.
It can be used in various hardware
It is useful in applications where high priority
applications where waiting will not cause
processes cannot be kept waiting.
any serious issues.
OS by JJsir

SHREE H. J. DOSHI INFORMATION TECHNOLOGY INSTITUTE JAMNAGAR

OPERATING SYSTEMS
BY JJ SIR

CH-2 : DEADLOCKS MEMORY MANAGEMENT


OS by JJsir

What is Deadlock in Operating System?

 A process in operating system uses resources in the


following way.
 Requests a resource
 Use the resource
 Releases the resource
 A deadlock is a situation where a set of processes
are blocked because each process is holding a
resource and waiting for another resource acquired
by some other process.
OS by JJsir

Deadlock

 Deadlock can arise if the following four conditions


hold simultaneously
 Mutual Exclusion: Two or more resources are non-
shareable (Only one process can use at a time)
 Hold and Wait: A process is holding at least one resource
and waiting for resources.
 No Preemption: A resource cannot be taken from a
process unless the process releases the resource.
 Circular Wait: A set of processes waiting for each other
in circular form.
OS by JJsir

Methods for handling deadlock

 Deadlock Prevention:
 The idea is to not let the system into a deadlock state.
 This system will make sure that above mentioned four conditions will not
arise.
 These techniques are very costly so we use this in cases where our
priority is making a system deadlock-free.
 One can zoom into each category individually, Prevention is done by
negating one of the above-mentioned necessary conditions for
deadlock.

 Prevention can be done in four different ways:


 1. Eliminate mutual exclusion 3. Allow preemption
 2. Solve hold and Wait 4. Circular wait Solution
OS by JJsir

Methods for handling deadlock

 Deadlock Avoidance:
 Avoidance is kind of futuristic.
 By using the strategy of “Avoidance”, we have to make an
assumption.
 We need to ensure that all information about resources that the
process will need is known to us before the execution of the process.
 In prevention and avoidance, we get the correctness of data but
performance decreases.
OS by JJsir

Methods for handling deadlock

 Deadlock Detection :
 A deadlock can be detected by a resource scheduler as it keeps
track of all the resources that are allocated to different processes.
 After a deadlock is detected, it can be resolved using the following
methods −
 All the processes that are involved in the deadlock are
terminated. This is not a good approach as all the progress made
by the processes is destroyed.
 Resources can be preempted from some processes and given to
others till the deadlock is resolved.
OS by JJsir

Physical Memory and Virtual Memory

 Physical Memory:
 Physical memory is the actual real memory used in RAM.
 Physical memory is the only memory that is directly accessible to the CPU.
 CPU reads the instructions stored in the physical memory and executes them
continuously.
 The data that is operated will also be stored in physical memory in uniform
manner.
 Virtual Memory:
 Virtual memory as the name suggests is not real.
 The OS uses virtual memory as a memory management technique in which
non- contiguous memory is presented to software as contiguous memory.
 Virtual memory is one classification of memory which was created by using
the hard disk for simulating additional RAM, the addressable space
available for the user.
 Virtual addresses are mapped into real addresses.
OS by JJsir

Memory Allocation

 Memory is a device whose work to store your data


and manage your computer applications

 When a user opens an application or program and any files


opened on that application, they are loaded into the RAM.

 Before loading, OS checks whether enough memory space is


there or not

 RAM is the temporary or volatile storage area utilized by the


CPU (Central Processing Unit). With RAM, you can both read
and write data.
OS by JJsir

Memory Allocation

 Two types of memory management are performed during the operation of


OS.
1).Memory allocation.
2).Memory deallocation.
 Memory Allocation:-
 Memory allocation is the act of managing computer memory.
 Memory Deallocation:-
 Freeing memory for reuse when no longer needed

 There are two types of memory management


 Contiguous memory management

 Non contiguous memory management


OS by JJsir

Fragmentation

 In a computer storage system, as processes are loaded and removed from


memory, the free memory space is broken into small pieces.
 In this way memory space used inefficiently, so the capacity or performance
of the system may degrade.
 The conditions of the fragmentation depend on the system of memory
allocation. In most of the cases, memory space is wasted.
 Sometimes it happens that memory blocks cannot be allocated to processes
due to their small size and memory blocks remain unused. This problem is
known as fragmentation.

 Types of fragmentation
1. External fragmentation
2. Internal fragmentation
OS by JJsir

Internal and External Fragmentation

 External fragmentation
 External fragmentation exists when total memory space
exists to satisfy a request, but it is not contiguous; storage
is fragmented into many holes.

 Internal fragmentation
 An approach is to allocate small holes as part of the
larger request. Thus, the allocated memory may be larger
than the requested memory.
OS by JJsir

Contiguous memory management

 Contiguous memory allocation is a classical memory allocation model that assigns a


process consecutive memory blocks (that is, memory blocks having consecutive
addresses).
 Contiguous memory allocation is one of the oldest memory allocation schemes.
 When a process needs to execute, memory is requested by the process. The size of
the process is compared with the amount of contiguous main memory available to
execute the process.
 If sufficient contiguous memory is found, the process is allocated memory to start its
execution.
 Otherwise, it is added to a queue of waiting processes until sufficient free
contiguous memory is available.
 There are different types of contiguous memory allocation in operating system.
1. Single partition allocation
2. Multiple Partition allocation
3. Dynamic partition allocation
OS by JJsir

Types of Contiguous memory management

 Single Partition Allocation


 In this scheme Operating system is residing in low memory and
user processes are executing in higher memory
 Multiple Partition Allocation

 User memory is divided into more than one partitions. There


are two types fixed partition or static partition and variable
partition or dynamic partition.
 Dynamic Partition Allocation

 If more than one empty space or blocks are available for an


active process, then the operating system decides how to select
a best space or block using dynamic allocation algorithms.
OS by JJsir

Noncontiguous memory allocation

 Non-contiguous allocation, also known as dynamic or linked allocation, is a


memory allocation technique used in operating systems to allocate memory to
processes that do not require a contiguous block of memory.
 In this technique, each process is allocated a series of non-contiguous blocks of
memory that can be located anywhere in the physical memory.
 Non-contiguous allocation involves the use of pointers to link the non-contiguous
memory blocks allocated to a process.

 There are two types of noncontiguous memory allocation.


 1. Paging
 2. Segmentation
OS by JJsir

Virtual Memory Using Paging

 Paging is based on the concept of dividing the programs into equal sized blocks called pages and
the main memory is divided into equal sized blocks known as frames.
 Generally the size of the page is equal to size of the frames so that there is no internal
fragmentation.
 Its not necessary that these frames are in sequence
 To know which page is loaded in which frame, for that page map table is used (PMT)
 PMT has two entries page number and its respective frame number. Each job will have its unique
PMT.
 This PMT also store somewhere in the memory and it has its own location and address.
 This location of PMT is stored in another table known as job table
 It contains two entries job number and location of PMT for each job
 Third table which is used is Memory Map Table (MMT)
 This table keeps track of free and busy frames in the main memory.
 Whenever new job arrives and new frames have to be allocated to this job, only those frames which
are free or unallocated to any jobs can be allocated to this job.
 Memory Map Table contains the frame numbers and its status of free or busy
OS by JJsir

Virtual Memory Using Segmentation

 Segmentation is based on the concept dividing programs into unequal sized


logical segments.
 For example if we want to divide the C language into logical segments, we can
divide it into various segments like variables, functions etc
 These segments loaded in the main memory
 To know which segment is loaded in which location of the main memory for that
OS uses Segment Map Table (SMT)
 SMT contains entries like segment number, starting address or base address,
size or limit of the segment.
 Each job has its unique SMT
 Here also job table is used, which contains number and location of its SMT and
MMT (memory map table) is also used to monitor the allocation of the memory
locations to the new incoming jobs.
OS by JJsir

SHREE H. J. DOSHI INFORMATION TECHNOLOGY INSTITUTE JAMNAGAR

OPERATING SYSTEMS
BY JJ SIR

CH-3 : GETTING STARTED WITH UNIX UNIX SHELL COMMAND


OS by JJsir

Unix Architecture

 The kernel is the heart of operating system.


 Its is loaded into main memory when the system boots.
 It performs two most basic functions of the operating
system like process management and resource
management
 It allocates the resources to the processes, manage
process scheduling, managing system and all other
communications with hardware
OS by JJsir

Unix Architecture

 Shell is another important component of unix


architecture.
 No user can directly communicate with the kernel.
 The users communicate with the shell. It analyses the
user’s command and its argument and converts it into
the language which the kernel can understands.
 Shell works as an interpreter between the user and
the kernel and kernel converts it into language which
the hardware can understand
OS by JJsir

Feature of Unix

 Multi user
 Multi tasking
 Portable
 Pattern Matching
 Tool Kit
 Programming Facility
 System calls & Libraries
 Window system
 Documentation
 Networking
 Organized file system
 Device Independence
OS by JJsir

Types of shell (C, Bourn, Korn)

Shell

BOURNE C Korn

Bash tcsh
OS by JJsir

Bourn Shell

 Bourne shell was developed by Steve Bourne at AT&T bell


labs and first released in 1977 in the Version 7 UNIX
release distributed to colleges and universities
 It was use in earlier versions of unix.
 It’s later version called Bash Shell
 The Bourne shell was the default Unix shell of Unix Version
7, and replaced the original Unix shell.
 Bourne shell introduced the feature of using file descriptor
for error messages and keeping error messages separate
from data. It works as commanding interpreter as well as
programming language.
 Shell is also known as the universal shell.
OS by JJsir

C Shell

 C shell was developed by William Joy at university


of California, Berkeley.
 It can be used to interpret user commands and also as
a programming language to create shell scripts
 There are three standard streams supported by C
Shell, standard input, standard output and standard
error
 C shell allows you to store values into variables.
OS by JJsir

C Shell

 C Shell executes any command in six sequential steps :


 It describe the command into words.
 It looks for the variable names starting with $ sign.

 It looks for the command substituted using back quotes.

 It checks the command for the redirected files and verifies the
files.
 If wildcard characters are found, shell replaces it with the
original file names.
 It uses the path variable to locate the directory containing the
actual command.
OS by JJsir

Korn Shell

 The Korn Shell was developed by David G. Korn at AT&T Bell


Laboratories.
 The major advantage of ksh over other shell are
 It allows users to use vi or emacs-style editing commands on
your command lines.
 It provides the functionality of several external UNIX
commands, including test, expr and echo.
 Utilities like grep and awk, have been added to the
standard set of filename to the shell variable facility.
 Advanced I/O features, including the ability to do two-way
communication are included in the korn shell.
OS by JJsir

Unix file system

 All utilities, application, data in Unix is stored as files


 Even directory treated as file, which contains several other files
 Bin – The bin directory contains executable files for most of
Unix commands.
 Lib – The lib directory contains all the library functions
provided by Unix for programmer
 Dev – Contains files that control various I/O device like printer,
disk drives etc
 Usr – In usr directory there are several directories, each
associated with a particular user.
OS by JJsir

Types of files

 File is a container for storing information


 In Unix, directories & devices are also treated as files
 A directory is simply a folder where you store
filename & other directories
 There are three types of file
 1) Ordinary files
 2) Directory files
 3) Device files
OS by JJsir

Ordinary File

 This file also known as Regular file and its also most common type
of file
 It can be a program code, executable file, data file or external
Unix command
 These regular files can store data either in text or binary format.
 The most common type is the text file.
 The data stored in these file is divided into group of lines
separated by the newline character.
 Another type of file is binary file. These are stored in the internal
format containing the application data.
 There are two types of binary files data files and program files.
A program file contains the set of instructions which can be
executed one after another
OS by JJsir

Directory files

 Directory file keep details of files of subdirectories.


 Directory file contains entry for each file & subdirectory.
 Each line in a directory file contains only the name of item &
location of item
 Every file is identified with the help of a unique inode number.
 Directory contains the list of files stored in it and its inode
number.
 We cannot create the files with same names in the same
directory but we can have the files with same names in another
directory.
OS by JJsir

Device Files

 Unix considers all the physical devices as files. This


devices may include printers, hard disk etc
 Any input given to this file will be redirected to the
respective physical device.
 When any command is issued to this file it is given as
an input to this file and the respective device
generates the output according to the parameters
passed to this file
OS by JJsir

Unix File & Directory permissions

 The Unix file system allows you to control read, write & execute access to
your files
Basic permission :-
1) Read permission :-
 Which grant the ability to read a file
2) Write permission :-
 Which grant the ability to modify a file when set for directory, this permission grant
the ability to modify entries in directory
 This includes creating files, deleting & renaming files
3) Execute permission :-
 Which grant the ability to execute a file.

 r – indicate read permission


 w – indicates write permission
 x – execute permission
OS by JJsir

Login Commands (Login And Logout)

 Since the unix/linux multi user system, the users are given their
own username by the system administrator
 User has to enter username and password when the prompt
appears on the screen

 Login: jignesh <enter>


 Password :

 Where jignesh is username it also known as userid or login


name.
 The string for password that you enter will not display on the
screen
OS by JJsir

Login Commands (Login And Logout)


 If you are enter either the login name and password incorrectly , the
system will display the following message

 Login incorrect
 Wait for login retry
 Login :

 After successful login system will show $ as a prompt. If you are the
system administrator and logged in as root, it will give the prompt #
 In LINUX prompt will be

 [root@localhost]#

 Which shows you are logged in as root and your machine is local host
 Logout is used to signoff a system as current user
OS by JJsir

Password command

 Password command is used to change password


 $password
 Old password:
 New password:
 Re-enter new password:

 When invoked by ordinary user, it asks for old


password.
 After which it demands to enter new password twice.
If you are logged in as root you can directly change
the password
OS by JJsir

Who, Who am I command, Clear, Uname


 Who command gives the list of the users currently working on various terminals
 $who
 yuvraj tty10 Dec 17 19:00
 darsh ty10 Dec 17 19:00
 $who –Hu
 USER LINE LOGINTIME IDLE FROM
 yuvraj tty10 Dec 17 19:00
 darsh ty10 Dec 17 19:00
 -H is for Header and –u option provides more detailed list
 Who am I command :
 The who command, when used with the arguments “am” and “i”, displays a single line output only
about current user.
 Clear command :
 This command is use when user want to clear screen
 $clear
 Uname command :
 Prints the name, version and other details about the current machine and the operating system.
 $uname
OS by JJsir

File / Directory Related Command - Cat (Concatenate)

 Cat(concatenate) command is very frequently used in Linux.


 It reads data from the file and gives their content as output.
 It helps us to create, view, concatenate files.
 There is three use of cat command
 To create file we can use cat command
 Cat > (filename)
 Cat > jj
 After edit in file you can save file by ctr+d
 To display file content use cat command
 Cat (filename)
 Cat jj
 To append file at the end we can use cat command
 Cat >> filename
 Cat >> jj
 After edit in file you can save file by ctr+d
OS by JJsir

File / Directory Related Command

 Ls
 This command is use to give list of files and directories created by user and
default
 Ls enter
 Clear
 To clear command prompt use clear to clear screen
 To clear with short cut key use ctr+l
 Ctrl + p
 You can use a combination of 'CTRL + P' and 'CTRL + R' to output the last
command that you used on the terminal.
 Pwd
 Pwd means Present(Print) woking Directory
 This command use to give current location of the user
 Pwd enter
OS by JJsir

File / Directory Related Command

 Mkdir :- (Make Directory)


 This command is use to create directory
 Mkdir filename
 Mkdir a b c
 Above command create three directory

 -P when we use mkdir with –p we can create


multilple subdirectory inside each directory
 Mkdir –p clg/fy/sy
 Above command create parent clg directory inside it fy
and inside fy sy directory
OS by JJsir

File / Directory Related Command

 cp - copying files
 eg. cp file1 file2 jj/
 -i : Interactive copy.1
 If the destination file already exists then interactive copy asks the user
whether the file should be overwritter or not? yes/no. If no is specified then
the copy command is terminated
 eg. cp -i file1 jj/
 -r : Recursive copy.
 It copies directory and its all sub directories and all files contained in
it to new directory. If the destination directory does not exist then first the
directories are created then the files are copied to them.
 eg. cp -r jj /kd
 cp * kd/
 It copies all files to directory
OS by JJsir

File / Directory Related Command

 Mv command :-
 Mv Command is use to rename directory and file another use of mv command is to move file and
directory in particular folder
 Rename
 Mv oldfilename newfilename
 Mv a abc (it will change name a from abc)

 Move file or folder


 It is use to move files or folders in to directory
 Mv a b/ (it will move a file to b directory)

 Mv –i
 When this command use with –i it will asks for overwrite if file already exist
 Mv –i a b/

 Mv –f
 When this command use with –f it will not ask for overwrite if file already exist
 Mv –f a b/

 Mv *
 move all files and directory to puticular folder
 Mv * b/
OS by JJsir

File / Directory Related Command

 Rmdir
 It removes directory if directory is empty
 Rmdir d
 Rm
 This command is use to remove file
 Rm f1
 Rm -i
 When rm use with –I it will ask before delete
 Rm –I f (it will ask user before delete if user type y it will delete if n
then file will not delete)
 Rm –r
 If rm command use with –r user can remove directory and its
subdirectories with all content
 Rm –r d
OS by JJsir

File / Directory Related Command

 Chgrp command:
 The `chgrp` command in Linux is used to change the
group ownership of a file or directory. All files in
Linux belong to an owner and a group.
 Chgrp [option] filename

 Chown command:
 The chown command in Linux changes user ownership
of a file, directory, or link(soft link or hard link) in
Linux.
 chown –version
OS by JJsir

Chmod command

 In Unix operating systems, the chmod command is used


to change the access mode of a file.
 The name is an abbreviation of change mode.
 Which states that every file and directory has a set of
permissions that control the permissions like who can
read, write or execute the file.
 In this the permissions have three categories: read,
write, and execute simultaneously represented by `r`,
`w` and `x`.
 These letters combine together to form a specific
permission for a group of users.
OS by JJsir

Chmod command

 The `chmod` command is used to modify this


permission so that it can grant or restrict access to
directories and files.
 Syntax:
 chmod [options] [mode] [File_name]
OS by JJsir

Symbolic mode (Chmod command)

 If we talk about symbolic mode, we can say that it


is the most common method used for specifying fir
permissions.
 In this we have to make a combination
of letters and operators to set or tell what to do
with permissions.
OS by JJsir

Chmod command

 The following operators can be used with the


symbolic mode:

Operators Definition

`+` Add permissions

`-` Remove permissions

Set the permissions to the specified


`=` values
OS by JJsir

Chmod command

 The following letters that can be used in symbolic


mode:
Letters Definition

`r` Read permission

`w` Write permission

`x` Execute permission


OS by JJsir

Chmod command

 The following Reference that are used:

Reference Class

u Owner

g Group

o Others

a All (owner,groups,others)
OS by JJsir

Chmod command

 Examples of Using the Symbolic mode:


 Read, write and execute permissions to the file
owner:
 chmod u+rwx [file_name]
 Remove write permission for the group and others:
 chmod go-w [file_name]
 Read and write for Owner, and Read-only for the
group and other:
 chmod u+rw,go+r [file_name]
OS by JJsir

File / Directory Related Command

 More = to view a text file one page at a time, press


spacebar to go to the next page
 more filename : show the document one page at a time
 Less= is much the same as more command except:
 You can navigate the page up/down using the less
command and which is not possible in more command.
 the usage : less filename
 Cd Command: cd command is used to change the
current working directory.
 The "cd" stands for 'change directory.'
 cd directoryname
OS by JJsir

File / Directory Related Command

 head = displays the first ten lines of a file, unless


otherwise stated.
 Examples
 head myfile.txt – Would display the first ten lines
of myfile.txt.
 head -15 myfile.txt – Would display the first fifteen lines
of myfile.txt.

 tail = display the last part of the file


 usage : tail filename
 tail -n filename : display the last n lines of the file
OS by JJsir

File / Directory Related Command

 The wc (word count)


 command in Unix/Linux operating systems is used to find out
number of newline count, word count, byte and
characters count in a files specified by the file arguments.

 The syntax of wc command as shown below.


 wc [options] filenames

 wc -l : Prints the number of lines in a file.


 wc -w : prints the number of words in a file.
 wc -c : Displays the count of bytes in a file.
OS by JJsir

File / Directory Related Command

 touch command:
 It is used to create a file without any content.
 The file created using the touch command is empty.
 This command can be used when the user doesn’t
have data to store at the time of file creation.
 Touch filename
 Ln command:
 The ln command is used to create links between files.
 ln -s sourcefile symboliclink
OS by JJsir

File / Directory Related Command

 Stat Command:

 The stat is a command which gives information about the


file and filesystem.
 Stat command gives information such as the size of the file,
access permissions and the user ID and group ID, birth time
access time of the file.
 Stat command has another feature, by which it can also
provide the file system information.
 This is the best tool to use when we want the information of
any file.
 Stat filename
OS by JJsir

File / Directory Related Command

 Alias command:

 alias are like custom shortcuts used to represent a command (or set
of commands) executed with or without custom options.
 It is like a shortcut command which will have same functionality as if
we are writing the whole command.
 The syntax for creating an alias is:
 alias name="value"
 $ alias .=cd
 To see all defined aliases in a reusable format, we can use the -
p option.
 $ alias -p
OS by JJsir

File / Directory Related Command

 Remove alias:
 We can remove an alias by using
the unailas command.
 syntax: unalias [alias name]
 $ unalias vi
 Find command: This command examines the
directory tree to for files matching the criteria and
then takes action on the selected files
 $find filename
OS by JJsir

File / Directory Related Command

 Type command:
 The type command is used to describe how its
argument would be translated if used as commands.
 It is also used to find out whether it is built-in or
external binary file.
 Syntax:
 type [Options] command names
 Example:
OS by JJsir

Type (Option)

 -a : This option is used to find out whether it is an


alias, keyword or a function and it also displays the
path of an executable, if available.
 Example:
 type -a pwd
OS by JJsir

Type (Option)

 -t : This option will display a single word as an output.


 alias – if command is a shell alias
 keyword – if command is a shell reserved word
 builtin – if command is a shell builtin
 function – if command is a shell function
 file – if command is a disk file
OS by JJsir

Operators

 In Unix redirection is to send O/P from process to different device


or another process read its I/P from different file, device or pipe.

 in Unix OS each command and process is automatically assigned 3


data streams
 1) one I/P stream called as standard i/p
 2) standard O/P
 3) standard error

 All consist of plain text and are considered as type of text file, and
all are associated with console (text mode display screen by
default)

 standard input is the source of input for command but it can be


redirected to come from some other source such as file or another
program
OS by JJsir

Operators in Redirection

 Standard output and standard error are the destination of output and
error messages from command but they can be redirected to go other
destination (file, printer or another program)
 Redirection device can be classified into 2 categories :
 1) argument
 2) redirection operators
 Arguments is the name of file or other data that is provided to command in
order for command to use it as input and it redirects standard I/P from
being the keyboard to that file or data

 Example :- if you want to read single file data then argument will be
 $ head file1
 Standard I/P could just as easily redirected with multiple argument
 Eg –$ head file1 file2 file3
 It this case head will by default read the 1st 10 lines from each file and
write them to display screen
OS by JJsir

Operators in Redirection

 Redirection operator :-
 1) I/p
 2) O/P
 3) Error
 To redirect standard I/p, so that command obtains its I/p from a file instead
of keyboard, the I/P redirection operator, which is represented by leftward
point angular bracket, cant be used(<)
 Eg – the standard I/p for head can be redirected to file named file 4 with
the following
 $ head < file 4
 And same by using argument
 $ head file 4
OS by JJsir

Operators in Redirection

 Standard O/P & standard error both are by default


the display screen.
 The O/p redirection operator(>) can be used to
redirect standard O/p
 Eg – the O/p of cat command can be used to read
files, it could be redirected when reading a file5
from displayed screen to file name file6
 $ cat file5 > file6
 The content of file5 are written to file6 and are not
visible on display monitor
OS by JJsir

Operators in Redirection

 File descriptor is numerical identifier maintained by OS


 0 standard I/P
 1 standard O/P
 2 standard error
 One of the act that produce error message is the use of name
of non-existent file as an argument for command.
 Eg - $ head no file
 In this case error message similar to following will appear on
new line on monitor head
 : no file :no such file or dir.
OS by JJsir

Operators in Piping

 Piping is used in one of the following ways: to tell command to


read its input from another command’s output, or to tell each
command in a string of commands to get its input from output of
the last command
 A common use for pipes is to control the output of large files to
the screen.
 Its possible to send output to the more command so that only
one screenful at a time is output
 The commands sort and grep are often used when piping.
 eg. :- $cat file1|grep jj
OS by JJsir

Finding Patterns in Files

 GREP – Global Regular Expression Print


 Grep means globally search for the regular
expression and print the matching lines.
 This utility was developed by Ken Thompson in
1968
 This command searches for pattern in one or more
text files
 It scans line by line for finding the occurrence of
pattern
Note:-Same for fgrep ,egrep
OS by JJsir

Finding Patterns in Files

 Syntax
 Grep options pattern filename
 Eg. :- grep ch JJ
 Arguments
 i – ignoring the case. Eg grep –i th jj
 w - grep makes it match only the whole words.
 Eg. grep -w "unix" jj
 c – counting the occurances. Eg. grep –c th jj
 I – displaying the file names. Eg. grep –l th *.txt
 n – displaying the line number. Eg. grep –n th jj
 ^ - This can be used in grep to match the lines which start
with the given string or pattern. Eg. Grep “^o” jj

Note:-Same for fgrep ,egrep


OS by JJsir

Working with columns/fields (Cut command)

 Linux cut command is useful for selecting a specific column of a file.


 It is used to cut a specific sections by byte position, character, and
field and writes them to standard output.
 It cuts a line and extracts the text data. It is necessary to pass an
argument with it; otherwise, it will throw an error message.
 To cut a specific section, it is necessary to specify the delimiter.
 A delimiter will decide how the sections are separated in a text file.
 Delimiters can be a space (' '), a hyphen (-), a slash (/), or anything
else. After '-f' option, the column number is mentioned.
 Syntax:
 cut OPTION... [FILE]...
OS by JJsir

Arguments in cut command

 -b, --bytes=LIST: It is used to cut a specific section


by bytes.
 -c, --characters=LIST: It is used to select the
specified characters.
 -d, --delimiter=DELIM: It is used to cut a specific
section by a delimiter.
 -f, --fields=LIST: It is used to select the specific
fields. It also prints any line that does not contain
any delimiter character.
OS by JJsir

Bytes Arguments

 -b(byte): To extract the specific bytes, you need to


follow -b option with the list of byte numbers
separated by comma.
 Range of bytes can also be specified using the
hyphen(-).
 It is necessary to specify list of byte numbers
otherwise it gives error.
 Tabs and backspaces are treated like as a
character of 1 byte.
OS by JJsir

Bytes Arguments

 Eg.  Eg.
 List without ranges  List with ranges
 cut -b 1,2,3 state  $ cut -b 1-7 state
 And  Andra
 Aru  Aruach
 Ass  Assm
 Bih  Bihr
 Chh  Chhtti
 cut -b 1- state  $ cut -b -3 state
OS by JJsir

Character argument

 -c (character): To cut by character use the -c option.


 This selects the characters given to the -c option.
 This can be a list of numbers separated comma or a
range of numbers separated by hyphen(-).
 Tabs and backspaces are treated as a character.
 It is necessary to specify list of character numbers
otherwise it gives error with this option
OS by JJsir

Character argument

 cut -c 2,5,7 state  cut -c 1-7 state


 nr  Andhra
 rah  Arunach
 sm  Assam
 ir  Bihar
 Hti  Chhatti
 Above cut command  Above cut command
prints second, fifth and prints first seven
seventh character from characters of each line
each line of the file. from the file.
 cut -c 1- state  cut -c -5 state
OS by JJsir

Line & Field argument

 -f (field): -f option is useful for fixed-length lines.


 Most unix files doesn’t have fixed-length lines.
 To extract the useful information you need to cut by
fields rather than columns.
 List of the fields number specified must be separated
by comma.
 Ranges are not described with -f option.
 cut uses tab as a default field delimiter but can also
work with other delimiter by using -d option.
Syntax:
 $cut -d "delimiter" -f (field number) file.txt
OS by JJsir

Line & Field argument

 cut -d " " -f 1 state.txt


 Andhra
 Arunachal
 Assam
 Bihar
 Chhattisgarh
OS by JJsir

Paste

 paste - It combines the files vertically

 eg. paste file1 file2

 -d delimiter list : it display files separated by


symbol instead of tab

 eg. paste -d '$' file1 file2


OS by JJsir

Join

 join - its use to join two files with same column

 eg. join file1 file2


OS by JJsir

Tools for sorting

 Sort command - this command is used for arranging data in


ascending or descending order.

 It sorts the data according to the ASCII values of the


characters.

 eg. sort jj

 -r sort the file in reverse order

 eg. sort -r jj
OS by JJsir

Sort a column

 If a file has more than one column, column number is


used to sort a specific column.
 Syntax:
 sort -k<columnNumber> <fileName>
 Example:
 sort -k1 states.txt
 sort -k2 states.txt
OS by JJsir

Numeric Sorting

 Numeric sorting is different from alphabetical


sorting. For numeric sorting option 'n' is used along
with the column number if required.
 Syntax:
 sort -n -k<columnNumber> <fileName>
 Example:
 sort -n -k2 marks.txt
OS by JJsir

Uniq command

 This command is used to selects non repeated line and removes other
duplicate lines from the output

 -u It removes duplicate lines and displays only the uniq lines from the file

 eg. uniq -u jj

 -d displays only the duplicate line

 eg. uniq -d jj

 -c count the number of duplicate lines in the file

 eg. uniq -c jj
OS by JJsir

Comparing files

 Cmp command:
 This command compares two files byte by byte the
first byte of first file compare with first byte of
second file

 cmp jj dj
OS by JJsir

Comm command

 This command is useful to compare two files line by line and displaying the common lines between
these files

 eg. comm jj dj

 the output consists of three columns the first column is the lines which are unique to the first file.
 the second column displays the lines which are unique to the second file.
 the third column displays the lines which are common between both files.

 Output
 a e
 b
 c

 d f
OS by JJsir

Diff command

 Diff stands for difference.


 This command is used to display the differences in
the files by comparing the files line by line.
 This command is used to Compare the contents of
file1 and file2 and write to the standard output the
list of changes necessary to convert one file into the
other
 eg. diff jj dj
OS by JJsir

Diff command

 The important thing to remember is that diff uses


certain special symbols and instructions that are
required to make two files identical.
 It tells you the instructions on how to change the first
file to make it match the second file.
 Special symbols are:
a : add
 c : change

 d : delete
OS by JJsir

Diff command

 diff [options] File1 File2


 Lets say we have two files with names a.txt and b.txt containing 5 Indian states.
 $ ls a.txt b.txt
 $ cat a.txt
 Gujarat
 Uttar Pradesh
 Kolkata
 Bihar
 Jammu and Kashmir
 $ cat b.txt
 Tamil Nadu
 Gujarat
 Andhra Pradesh
 Bihar
 Uttar pradesh
OS by JJsir

Diff command

 $ cat a.txt  Now,


 Gujarat applying diff command
 Uttar Pradesh without any option we get
 Kolkata the following output:
 Bihar  $ diff a.txt b.txt
 Jammu and Kashmir  0a1
 > Tamil Nadu
$ cat b.txt

 2,3c3
 Tamil Nadu
 Gujarat
 < Uttar Pradesh
 Andhra Pradesh  Andhra Pradesh
 Bihar  5c5
 Uttar pradesh  Uttar pradesh
OS by JJsir
Changing Information in Files
(Translate/ tr Command)
 Tr stands for translate.
 The tr utility in unix or linux system is used to translate, delete or squeeze
characters. The syntax of tr command is
 tr [options] set1 [set2]
 Translate from upper to lower or lower to upper
 eg. echo "linux dedicated server" | tr "[:lower:]" "[:upper:]"
 output :- LINUX DEDICATED SERVER

 eg. echo "linux dedicated server" | tr "[a-z]" "[A-Z]"


 output :- LINUX DEDICATED SERVER

 Replace white space with special symbol or character


 Eg. Echo “hello world”|tr “[:space:]” “_”
 Output hello_world_
OS by JJsir

(Translate/ tr Command)

 The options of tr command are:

 -c : Replace non-matching characters.


 -d : deletes the characters in set1
 -s : replaces repeated characters listed in the set1
with single occurrence
OS by JJsir

-c option

 Replace non-matching characters.

 The -c option is used to replace the non-matching


characters with another set of characters.

 eg. echo "unix" | tr -c "u" "a"


 output :- uaaa
OS by JJsir

-d option

 Delete characters

 The following example removes the word linux from


the string.

 eg. echo "linuxserver" | tr -d "linux"


 output :- server
OS by JJsir

-s option

 replaces repeated characters listed in the set1 with


single occurrence
 eg. Echo “this is teest" | tr -s " e”
 output :- this is test
 Also use to replace characters from set 1
 Eg. Echo “this is test”|tr –s “ “ “$”
 Output :- this$is$test
OS by JJsir

SED command

 SED command in UNIX is stands for stream editor


and it can perform lot’s of function on file like,
searching, find and replace, insertion or deletion.
 Most common use of SED command in UNIX is for
substitution or for find and replace.

 Syntax:
 sed OPTIONS... [SCRIPT] [INPUTFILE...]
OS by JJsir

Replacing or substituting string

 Sed command is mostly used to replace the text in a file.


 The below simple sed command replaces the word “unix”
with “linux” in the file.
 sed 's/unix/linux/' jsed
 Here the “s” specifies the substitution operation.
 The “/” are delimiters.
 The “unix” is the search pattern and the “linux” is the
replacement string.
 By default, the sed command replaces the first occurrence
of the pattern in each line and it won’t replace the
second, third…occurrence in the line.
OS by JJsir

Replacing the nth occurrence of a pattern


in a line
 Use the /1, /2 etc to replace the first, second
occurrence of a pattern in a line.

 The below command replaces the second occurrence


of the word “unix” with “linux” in a line.

 sed 's/unix/linux/2' jsed


OS by JJsir
Replacing all the occurrence of the
pattern in a line
 The substitute /g (global replacement) specifies the
sed command to replace all the occurrences of the
string in the line.

 sed 's/unix/linux/g' jsed


OS by JJsir

Deleting lines from a particular file

 1. To Delete a particular line  4. To Delete from nth to last line


 Syntax: sed 'nd' filename.txt  Syntax: sed 'nth, d' filename.txt
 Example: sed '5d' filename.txt  Example: sed '12, $d' filename.txt


 2. To Delete a last line
 5. To Delete pattern matching line
 Syntax: sed ' $d' filename.txt
 Syntax: sed '/pattern/d‘
 filename.txt
 3. To Delete line from range x to y
 Example: sed '/abc/d' filename.txt
 Syntax: sed 'x,yd' filename.txt
 Example: sed '3,6d' filename.txt
OS by JJsir

Examining File Contents (od command)

 Od means Octal Dump.


 This displays the contents as octal numbers.
 od command in Linux is used to convert the content of input in
different formats with octal format as the default format.
 This command is especially useful when debugging Linux scripts
for unwanted changes or characters.
 If more than one file is specified, od command concatenates
them in the listed order to form the input.It can display output
in a variety of other formats, including hexadecimal, decimal,
and ASCII.
 eg. od jj
OS by JJsir
Tools for mathematical calculations
(bc command)
 bc command stands for basic calculations.
 This command is used for basic calculations like
addition subtractions and so on..
 just write bc command and start your calculation when
you want to end just press ctr+d to exit from bc..

 eg. bc
 12*2 <enter>
 24
 ctr+d
OS by JJsir

factor

 This command finds the factors of an integer


 eg. factor

 12<enter>
 12:2 2 3

 20<enter>
 20 : ???
 ctr+d
OS by JJsir
Monitoring Input and Output
(Tee command)
 tee - tee is normally used to split the output of a program so that it can be
both displayed and saved in a file.

 The command can be used to capture intermediate output before the data
is altered by another command or program.

 The tee command reads standard input, then writes its content to standard
output.

 It simultaneously copies the result into the specified file(s) or variables

 eg. sort jj|tee jsort|head -3


 eg. sort jj|tee jsort|uniq -c


OS by JJsir

Script

 script - with use of script command you can record your session.

 To start script just write script followed by script name it


displays the message the script started.

 To end script just type exit it will exit from started script.

 To display recorded script just type cat followed by your script


name.

 eg. script jscript


 exit
 cat jscript
OS by JJsir
Tools For Displaying Date and Time
(Cal command)
 cal - cal command displays the simple calendar.

 If no arguments are supplied, by default it displays the calendar to


the current month.

 cal accepts the year value between 1 and 9999.

 eg. cal
 eg. cal 8 2016
 eg. cal 2018
 eg cal -j

 cal -j : It displays the Julian dates as 1st Jan as 01 and 31st Dec as 365
OS by JJsir

Date

 date : this command is used to print date. By


default it displays date and time.

 Example
 date

 Example
 date "+ %d %m %y"
OS by JJsir

Communications (Telnet)

 Telnet stands for Teletype Network


 Telnet is used to connect to the remote system using the telnet protocol.
 When this command is invoked it enters the command mode and displays a telenet prompt.
 In this mode it accepts the commands to be executed.
 command meaning
 ---------------------------------------------------------------------------------
 open connects to a remote computer
 close close the connection
 display it shows the parameters
 mode it used to change the character mode to line mode
 status it displays the status information
 When telenet is used with IP address of the remote system, it asks for username and password to enter the
system.
 After login whatever modification are done would be on the remote computer and your local computer would be
like a terminal without any resources.
 It also known as remote login
OS by JJsir

MOTD (Message Of The Day)

 To display message of the day at login time.


 The contents are displayed after a successful login
but just before it executes the login shell.
 The MOTD stands for “Message Of The Day”.
 This command is like your welcome note in your
mobile when you start your mobile, a message you
set already while you switch on your mobile, it
display on your mobile screen.
OS by JJsir

Wall

 This command is used to send a message to the terminals of


each user who are currently logged in.
 The message is passed as an argument to the wall command
or it can be sent using the standard input from the terminal.
 The message which displayed to the user contains the
header information like Broadcast message from the user,
current date and time and message
 To send message just type
 Wall press enter
 Hellow world
 Ctr+d to send message
 The length of the message is limited to 20 lines.
OS by JJsir

Write

 The write utility allows you to communicate with other users by


copying lines from your terminal to theirs.
 When you run the write command, the user you are writing to gets a
message of the format:
 Message from yourname@yourhost on yourtty at hh:mm ...Any
further lines you enter will be copied to the specified user's terminal.
 If the other user wants to reply, they must run write as well.
 When you are done, type an end-of-file.
 The other user will see the message ‘EOF’ indicating that the
conversation is over

 Example
 Write (username)
OS by JJsir

News

 This is command is used by the users to read the


messages received from the system administrator.
 When user logs into a multiuser system, announcements
of news placed by the administrator are displayed to
the user
 The news command displays the current news, with the
,most recent news first.
 Example
 $news
 Hello (root) Tue January 2 12:52 2017
 Meeting at 18:00pm
OS by JJsir

Finger

 It is known as user information look up program.


 When used without options it displays the
information about the users who are currently
logged in.
 It displays the login, full name, terminal type, idle
time, login time , the office location and office
phone number.
 This command is similar to who command but finger
can also provide information of a single user like
full name, home directory, shell, mail, plan details…
OS by JJsir

Mesg

 Mesg controls the access to your terminal by others.


It’s typically used to allow or disallow other users to
write to your terminal.
 Mesg assumes that its standard input is connected to
your terminal.
 That also means that if you are logged in multiple
times, you can get/set the mesg status of other
sessions by using redirection.

 Eg.mesg [y|n]
OS by JJsir

Ping

 Ping is short for Packet Internet Groper.


 This command is mainly used for checking the network
connectivity among host/server and host.
 The ping command takes the URL or IP address as
input and transfers the data packet to a specified
address along with a "PING" message.
 Then, it will get a reply from the host/server. This time
is known as "latency".

 Eg. ping www.google.com


OS by JJsir

Process Related Commands

 Ps
 Ps stands for Process Status
 This command displays the information about the active
processes.
 Eg. Ps
 Kill
 This command terminates the process associated with the
specified pid value.
 If more than one process has to be terminated it can be
done by single statement by specifying pid of all the
processes
 Eg. Kill 5254 5290 5230…..
OS by JJsir

Process Related Commands

 Nice :-
 Runs a command with a modified scheduling priority.
 nice runs command COMMAND with an adjusted "niceness",
which affects process scheduling.
 A process with a lower niceness value is given higher priority
and more CPU time. A process with a higher niceness value
(a "nicer" process) is given a lower priority and less CPU
time, freeing up resources for processes which are more
demanding.
 Niceness values range from -20 (most favorable to the
process) to 19 (least favorable to the process).
 With no COMMAND, nice prints the current niceness level.
OS by JJsir

Process Related Commands

 Batch and At
 Batch invoke at command
 The at command schedules a command to be run once at a particular time.
 This can be any command that you normally have permission to run;
anything from a simple reminder message, to a complex script.
 You start by running the at command at the command line, passing it the
scheduled time as the option.
 It then places you at a special prompt, where you can type in the command
(or series of commands) to be run at the scheduled time.
 When you're done, press Control-D on a new line, and your command will
be placed in the queue.

 Eg. at 9:30 PM Tue


OS by JJsir

Command to run process in background

 Cron and crontab :-


 The cron is a long-running process that executes
commands at specific dates and times.
 You can use this to schedule activities, either as one-time
events or as recurring tasks.
 To schedule one-time only tasks with cron, use
the at or batch command.
 For commands that need to be executed repeatedly
(e.g., hourly, daily, or weekly), you can use the crontab
command.
 The crontab command creates a crontab file containing
commands and instructions for the cron to execute.
OS by JJsir

Command to run process in background

 Wait
 wait is a built-in shell command which waits for a
given process to complete, and returns its exit status.
 Eg. Wait [pid]

 sleep
 The sleep command is used to delay for a specified
amount of time.
 Eg. Sleep 10
OS by JJsir

Command to run process in background

 jobs
 The jobs command allows you to view a list of all jobs running in the
background or suspended in the current shell.
 Eg. $jobs
 top
 The top command displays all the running process within the
environment of your system.
 It helps in monitoring system usage and performances. It is mainly
used to detect load on the server by system administrators.
 The top command stands for table of processes.
 Eg. top
OS by JJsir

Concept of Mounting and Unmounting a File System

 Mount
 The mount command mounts a storage device
or filesystem, making it accessible and attaching it
to an existing directory structure.
 Unmount
 The umount command "unmounts" a mounted
filesystem, informing the system to complete any
pending read or write operations, and safely
detaching it.
OS by JJsir

SHREE H. J. DOSHI INFORMATION TECHNOLOGY INSTITUTE JAMNAGAR

OPERATING SYSTEMS
BY JJ SIR

CH-4 : TEXT EDITING WITH VI AND NANO EDITOR, SHELL PROGRAMMING


OS by JJsir

Introduction of vi editor

 Unix provides editors to process the contents of the


files containing the text, source code or shell
programs.
 You can see part of file in a window on the screen
& editing operation can be controlled by moving
cursor around the text on screen
 Once you learn vi, you will find that its fast and
powerful editor
 Vi has no menu, but instead you use combination of
key strokes in order to accomplish commands.
OS by JJsir

Modes in vi

 There are three modes in vi editor


 1) Command mode
 2) Input mode
 3) Ex mode or last line mode
OS by JJsir

Command mode

 when you press vi with your file name or without


filename unix open vi editor by default its in
command mode
 The cursor positioned at the top an all remaining lines
of the screen show a ~.
 The last line is reserved commands that you can enter
to act on text
 This is the mode where you can pass commands to act
text, using most of the keys of the keyboard. You
cannot use this mode to enter or replace text
OS by JJsir

Input mode in vi

 To enter text, you must switch to the Input Mode.


 First press the key marked I, and you are in this
mode ready to input text
 Start entering a few lines of text, each line followed
by [Enter]
OS by JJsir

Ex mode or last line mode

 After text entry is complete, the cursor is positioned


on the last character of the last line
 This is known as the current line and the character
where the cursor is stationed is the current cursor
position.
 If you show something that shouldn’t be there, use
backspace key to wipe it out.
 If a word has been misspelled use (ctrl+w) to erase
the entire word
OS by JJsir

Switching mode in VI

 While you start VI editor at that time you will be at vi mode that will ready to accept
defined command on that particular key but not any input.
 If you want to input text into the file you will have to go to input mode for that you
will have to press “i”.
 If you will press “i” at VI mode you will be at input mode here you can input any data
into the file from this mode if you want to switch to vi mode then you will have to
press “Esc” key.
 If you will press “Esc” key at input mode you will be able to switch to vi mode.
 If you want to switch to command mode from the VI mode then you will have to press
“:” or “/” that will support you to switch you from VI mode to command mode.
 If you want to switch to command mode from the input mode then you will have to
first come to the VI mode then you will be able to switch to command mode.
 To switch from input mode to command mode then you first will have to press “Esc”
key and then after you will have to press “:” or “/” key that will support you to switch
from input mode to command mode via VI mode.
OS by JJsir

Cursor moment in vi editor

 h - left one charecter


 l - right one charecter
 b - moves back to the beginning of word
 w - moves forward to the beginning of the word
 e - moves forward to the end of word
 ) - move to the next sentence
 ( - move to the previouse sentence
 } - move to the next paragraph
 { - move to the previous paragraph
OS by JJsir

Screen control commands

 screen command in Linux provides the ability to


launch and use multiple shell sessions from a single ssh
session.
 When a process is started with ‘screen’, the process
can be detached from session & then can reattach the
session at a later time.
 When the session is detached, the process that was
originally started from the screen is still running and
managed by the screen itself.
OS by JJsir

Screen control commands (options)


 -a: It force all capabilities into each window’s termcap.  -p window: It preselect the named window if it exists.
 -A -[r|R]: It adapt all windows to the new display width &  -q: It quiet startup. Exits with non-zero return code if unsuccessful.
height.
 -Q: It commands will send the response to the stdout of the
 -c file: It read configuration file instead of ‘.screenrc’. querying process.
 -d (-r): It detach the elsewhere running screen (and reattach  -r [session]: It reattach to a detached screen process.
here).
 -R: It reattach if possible, otherwise start a new session.
 -dmS name: It start as daemon: Screen session in detached
 -S sockname: It name this session .sockname instead of …
mode.
 -t title: It set title. (window’s name).
 -D (-r): It detach and logout remote (and reattach here).
 -T term: It use term as $TERM for windows, rather than “screen”.
 -D -RR: It do whatever is needed to get a screen session.
 -U: It tell screen to use UTF-8 encoding.
 -e xy: It change the command characters.
 -v: It print “Screen version 4.06.02 (GNU) 23-Oct-17”.
 -f: It make the flow control on, -fn = off, -fa = auto.
 -x: It attach to a not detached screen. (Multi display mode).
 -h lines: It set the size of the scrollback history buffer.
 -X: It execute as a screen command in the specified session.
 -i: It interrupt output sooner when flow control is on.
 -l: It make the login mode on (update /var/run/utmp), -ln = off.
 -ls [match]: It display all the attached screens.
 -L: It turn on output logging.
 -m: It ignore $STY variable, do create a new screen session.
 -O: It choose optimal output rather than exact vt100 emulation.
OS by JJsir

Screen control commands (shortcut key)

 Ctrl-a + c: It create a new windows.


 Ctrl-a + w: It display the list of all the windows currently opened.
 Ctrl-a + A: It rename the current windows. The name will appear when you will list the list of windows
opened with Ctrl-a + w.
 Ctrl-a + n: It go to the next windows.
 Ctrl-a + p: It go to the previous windows.
 Ctrl-a + Ctrl-a: It back to the last windows used.
 Ctrl-a + k: It close the current windows (kill).
 Ctrl-a + S: It split the current windows horizontally. To switch between the windows, do Ctrl-a + Tab.
 Ctrl-a + |: It split the current windows vertically.
 Ctrl-a + X: Close active Split window
 Ctrl-a + Q: Close all Split windows
 Ctrl-a + d: It detach a screen session without stopping it.
 Ctrl-a + r: It reattach a detached screen session.
 Ctrl-a + [: It start the copy mode.
 Ctrl-a + ]: It paste the copied text.
OS by JJsir

Copy and paste in vi

 COPYING THE TEXT

 yy - copy the current line


 yw - copy the current word
 V or v – to select lines user wish to select for copy
 G – use this command in visual mode to select all from current cursor positoin
 d for cut and y for copy all selected text
 -----------------------------------------------------------
 PASTING THE TEXT

 p - Paste the text after the cursor position

 P - Paste the text before the cursor position


OS by JJsir

UNDO REDO in vi

 UNDO REDO in vi

 u - use for undo your last changes

 ctr+r - use for redo your last changes


OS by JJsir

Deleting the text

 x - Deletes the current character

 dd - Deletes the current line

 dw - Deletes word and the following space

 de - Deletes from the current charecter to the end of current word

 gg – it will to to first line

 dG – it will delete all line from the beginig


OS by JJsir

Introduction of nano editor

 Nano is a user-friendly, simple and


WYSIWYG(What You See Is What You Get) text
editor, which improves the features and user-
friendliness of UW Pico text editor.
 Unlike vim editor or any other command-line editor,
it doesn’t have any mode.
 It has an easy GUI(Graphical User Interface) which
allows users to interact directly with the text in spite
of switching between the modes as in vim editor.
OS by JJsir

Installing Nano Text Editor

 Nano is generally by default available in many


Linux distributions but in case, it is not installed you
may install the same using the following commands.
 $sudo apt update
 In case of Debian/Ubuntu
 $sudo apt install nano
 In case of CentOS/Fedora
 $yum install nano
OS by JJsir

Working with Nano Text Editor

 To create and open a new file.


 $nano new_filename
 The above command will open a new file with
new_filename as shown in the output.
 In case the file already exists it will open the same
and in case the file is not there in the current
directory it will create a new one.
 At the bottom of the window, there is a list of
shortcut keys for nano.
OS by JJsir

To create and open a new file


OS by JJsir

To save a file

 press Ctrl+o It will ask you for the filename.


 In case, you want to save the changes to a new file
or want to create a new file then change the name
else keep the name same.
 As soon as you will press enter key, then In case, you
have changed the name of the file then it will save
the file with a new name and if not then it will save
the changes to the current file.
OS by JJsir

To save a file
OS by JJsir

To cut paste in a file

 Ctrl+o is used to cut and Ctrl+u is used to paste the


text.
 To cut and paste a whole line. Move to the line which you
want to cut then press Ctrl+k.
 Now the line is moved to clipboard, To paste it, go to
the position where you want to paste and then
press Ctrl+u
 To cut and paste the selected text. Select the text which
you want to cut then press Ctrl+k.
 Now the text is moved to clipboard. To paste it, go to
the position where you want to paste and then
press Ctrl+u.
OS by JJsir

To cut paste in a file


OS by JJsir

To cut paste in a file


OS by JJsir

To search a word in a file

 Ctrl+w is used.
 Press Ctrl+w
It will ask for a word to search for.
Enter the word
It will search for the word and will place the cursor in
the first letter of the first occurrence of the word.
OS by JJsir

To search a word in a file


OS by JJsir

Shell Keywords

 Keyword is a word which is having specific meaning


for particular language.

echo read set unset


readonly shift export if
fi else while do
done for until case
esac break continue exit
return trap wait eval
exec ulimit umask
OS by JJsir

Shell Variables

 Variable is the location in the memory which is used to store the


data.
 A variable is a character string to which we assign a value.
 The value assigned could be a number, text, filename, device, or
any other type of data.
 The name of a variable can contain only letters (a to z or A to
Z), numbers ( 0 to 9) or the underscore character ( _).
 The following examples are valid variable names −
 _RAM
 TOKEN_A
 VAR_1
 VAR_2
OS by JJsir

Shell Variables

 Following are the examples of invalid variable names −


 2_VAR
 -VARIABLE
 VAR1-VAR2
 VAR_A!
 Defining Variables
 Variables are defined as follows −
 variable_name=variable_value
 Shell enables you to store any value you want in a variable.
 For example − VAR1="Rohit Sharma" VAR2=100
 Accessing Values
 To access the value stored in a variable, prefix its name with the dollar sign ($)
 #!/bin/sh
 NAME="Rohit Sharma "
OS by JJsir

System Variables

 These variables are used to configure the environment during the boot sequence or
after user login, so they are also known as environment variables.
 The shell has two prompts stored in PS1 and PS2.
 PS1: It is the primary prompt string like $ or %. The shell uses the primary prompt when
the command is expected by the shell. For changing the value of this prompt, we can
use PS1= ‘@’.
 As soon as it is set the new prompt is displayed. It can be restored back to $ prompt as
PS1=“$”.
 PS2: It is the secondary prompt; it is used when the command entered on the first line
was not able to be completed. The default prompt is >.
 PATH: Searches the path for commands. If $PATH is not set then the current directory,
/bin and /usr/bin are searched by default. Otherwise $PATH consists of directory
names
 separated by:
 For Example: PATH=:/usr/Bhavik/bin:/bin:/usr/bin
OS by JJsir

System Variables

 HOME: It is path name for the home directory. When the user logs in the
system, unix normally places the user in home directory or login directory and
is the path stored in variable HOME.
 The change the default argument for the cd command.
 For Example: cd /usr/Bhavik/bin
 LOGNAME: It contains login name which is stored in the passwd file. This
variable shows your username only while Who am I also displays the user
name with the terminal type and login name.
 MAIL: It displays the absolute path name of user’s mailbox and determines
where all incoming mail addressed to the user is to be stored. This variable is
typically set in the file .profile, in the user’s login directory.
 For Example: MAIL=/var/spool/mail/root
OS by JJsir

System Variables

 IFS: This variable contains internal field separators. These are the characters that
separate
 the parameters and commands. These separators include space, tab and newline.
Default
 separator is space.
 SHELL: This variable contains the pathname of login shell. Various shells available in
 unix system include korn shell, bash shell or c shell. User can select any one from them.
 TERM: It indicates the Terminal type being used. The value of this variable can be
 utilised by VI command. The VI editor makes the use of the control file in the directory
 /usr/lib/terminfo.
 MAILCHECK: It contains Interval between tests for new email. The default is 600
 seconds. When the user logs in, shell checks mail file to determine if there is new mail.
If mail is there, it display “You have a mail”.
OS by JJsir

User defined variables

 The variable which is created by the user is known as user defined


variables.
 1. The variable name should not be the same as one of the
predefined variables.
 2. The name of the variable must start with an alphabet or
underscore.
 3. Unix is case sensitive, so SUM and sum are treated as different
variables.
 set, unset, and echo command with variables
 You can use set command to set any variable.
 You can use unset command to unset/remove any variable.
 You can use echo command to print the value of any variable.
OS by JJsir

Positional Parameters

 A positional parameter is a variable within a shell program; its value is set from an argument
specified on the command line that invokes the program.
 Positional parameters are numbered and are referred to with a preceding ``$'': $1, $2, $3, and
so on.
 Example:
 $sh filename.sh first second third fourth fifth sixth seventh eighth ninth
$0 $1 $2 $3 $4 $5 $6 $7 $8 $9

 Arguments are user supplied data that follow the file name on the command line and are input to
the shell script.
 Positional Parameters are predefined memory variables in the shell scripts.
 There are nine positional parameters $1, $2……. $9 that are used to store the user arguments.
 The file name is stores in $0.
 When script is executed the shell puts the first argument in first positional parameter $1, second
argument in second positional parameter $2 and so on
OS by JJsir

Interactive Shell scripts

 The read command is a shell built-in command for reading data from a file or keyboard.
 The read command receives the input from the keyboard or a file until it receives a newline character. Then, it
converts the newline character into a null character:
 1. Read a value and store it in the variable, shown as follows:
 2. read variable
 3. echo $variable
 This will receive text from the keyboard. The received text will be stored in the variable.
 4. Command read with prompt. Whenever we need to display the prompt with certain text, we use the –p
option. The option -p displays the text that is placed after –p on the screen:
 5. #!/bin/bash
 6. # following line will print "Enter value: " and then read data
 7. # The received text will be stored in variable value read -p "Enter value : " value
 Output:
 Enter value : abcd
 8. If the variable name is not supplied next to the read command, then the received data or text will be stored
in a special built-in variable called REPLY.
OS by JJsir

The if...elif...fi statement

 The if...elif...fi statement is the one level advance form of control statement that
allows Shell to make correct decision out of several conditions.

 Syntax

 if [ expression 1 ] | if(( expression ))


 Then
 Statement(s) to be executed if expression 1 is true
 elif [ expression 2 ] | elif(( expression ))
 then
 Statement(s) to be executed if expression 2 is true
 Else
 else Statement(s) to be executed if no expression is true
 fi
OS by JJsir

The case...esac Statement

 The basic syntax of the case...esac statement is to


give an expression to evaluate and to execute
several different statements based on the value of
the expression.

 The interpreter checks each case against the value


of the expression until a match is found. If nothing
matches, a default condition will be used.
OS by JJsir

Case Syntax

 case word in
 pattern1)
 Statement(s) to be executed if pattern1 matches
 ;;
 pattern2)
 Statement(s) to be executed if pattern2 matches
 ;;
 *)
 Default condition to be executed
 ;;
 esac
OS by JJsir

Test command

 The test command is used to check file types and compare values. Test is used in conditional
execution.
 Syntax:
 test condition
 OR
 test condition && true-command
 OR
 test condition || false-command
 OR
 test condition && true-command || false-command
 Example :
 Type the following command at a shell prompt (is 5 greater than 2? ):
 test 5 -gt 2 && echo "Yes"
 test 1 -lt 2 && echo "Yes"
 Sample Output:
 Yes
 Yes
OS by JJsir

Logical Operator

 Logical Operators: They are also known as Boolean operators. These are used to perform logical operations.
 They are of 3 types:
 Logical AND (&& / -a): This is a binary operator, which returns true if both the operands are true otherwise
returns false.
 Logical OR (|| / -o): This is a binary operator, which returns true is either of the operand is true or both the
operands are true and returns false if none of them is false.
 Not Equal to (!): This is a unary operator which returns true if the operand is false and returns false if the
operand is true.
 Example:
 # take a number from the user
 echo "Enter a number: "
 read a
 # check
 if [ `expr $a % 2` == 0 -a $a -gt 10 ]
 then
 echo "$a is even and greater than 10."
 else
 echo "$a failed the test."
 fi
OS by JJsir

For loop

 syntax :
 For((statement 1, statement 2, statement 3))
 Do
 Statements to be excute
 Done

 Here statement1 is initializing variable


 Statement2 is condition like i<=10 etc

 Statement3 is increment or decrement like i++


OS by JJsir

While loop

 The while loop enables you to execute a set of


commands repeatedly until some condition occurs.
 Syntax:
 while [condition]
 do
 Statement(s) to be executed if condition is true
 done
OS by JJsir

Until loop

 Syntax :
 until [condition]
 do
 Statement(s) to be executed if condition is true
 done

 This loop continue until condition false when


condition come true loop exit
OS by JJsir

Break and continue

 Both “break” and “continue” are used to transfer


control of the program to another part of the
program.

 It is used within loops to alter the flow of the loop


and terminate the loop or skip the current iteration.
OS by JJsir

Break statement

 The break statement is used to terminate the loop and


can be used within a while, for and until loops.
 Example:
 for((i=1;i<=10;i++))
 do
 if [ $i -eq 3 ]
 then
 break
 fi
 echo $i
 done
OS by JJsir

Continue statement

 Continue is a command which is used to skip the remaining


command inside the loop for the current iteration in for, while,
and until loop.
 Example:
 for((i=1;i<=10;i++))
 do
 if [ $i -eq 3 ]
 then
 continue
 fi
 echo $i
 done
OS by JJsir

Difference between break and continue

Sr. No. break continue

It terminates the execution of the It skips the execution of the loop for
1
loop for all the remaining iterations. only the current iteration.

It allows early termination of the It allows early execution of the next


2
loop. iteration.

It stops the execution of the loop


3 It stops the execution of loops.
only for the current iteration.

The code in the loop continues its


The code after the loop which was
4 execution skipping the current
terminated is continued.
iteration.
OS by JJsir

Array

 An array is a structured arrangement of similar


data elements.
 Within shell scripting, an array is a variable that
holds multiple values, whether they are of the same
type or different types.
 It’s important to note that in shell scripting,
everything is treated as a string.
 Arrays adhere to a zero-based index, which
signifies that indexing initiates from 0.
OS by JJsir

How to Declare Array in Shell Scripting?

 1. Indirect Declaration
 In this method, you assign a value to a specific index of the array variable.
There’s no need to declare the array beforehand.
 ARRAYNAME[INDEXNR]=value

 2. Explicit Declaration
 With explicit declaration, you first declare the array and then assign values
to it.
 declare -a ARRAYNAME

 3. Compound Assignment
 This method involves declaring the array along with its initial set of values.
You can later add additional values to the array.
 ARRAYNAME=(value1 value2 .... valueN)
OS by JJsir

Printing Array Values in Shell Script

 # To declare a static Array


arr= (“Jayesh “Shivang” “1” “Vipul” “Nishant” “2”)
 # To print all elements of the array
 echo “All elements of the array:”
echo “${arr[@]}”
echo “${arr[*]}”
 # To print the perticular element
echo “The first element:”
echo “${arr[0]}”
OS by JJsir

Printing Array range & count in Shell Script

 # To print elements in a range


echo “Elements in a range:”
echo “${arr[@]:1:3}” # Prints elements from index 1
to 3
echo “${arr[*]:1:3}” # Prints elements from index 1
to 3
 # Count the length of the entire array
array_length=${#arr[@]}
echo “Length of the array: $array_length”
OS by JJsir

Count Array Element & delete in Shell Script

 # Count the length of a particular element in the


array
element_length=${#arr[2]}
echo “Length of element at index 2:$element_length”
 # Delete an element in the array (index 3)
unset arr[3]
 echo “Array after deletion: ${arr[*]}”
OS by JJsir

Search Array Element & Replace in Shell Script

 # Search and replace in the array


replaced_element=$(echo“${arr[@]/Shivang/SHIVA
NG}”)
echo “Array after search &
replace:${replaced_element[*]}”
OS by JJsir

UDF (Creating Functions)

 Using functions to perform repetitive tasks is an excellent


way to create code reuse.
 To declare a function, simply use the following syntax −
 function_name ()
 {
 list of commands
 }
 The name of your function is function_name, and that's
what you will use to call itfrom elsewhere in your scripts.
The function name must be followed by
parentheses,followed by a list of commands enclosed
within braces.
OS by JJsir

UDF (User Defined Function)

 Example:
 Following example shows the use of function −
 # Define your function here
 Hello ()
 {
 echo "Hello World“
 }
 # Invoke your function
 Hello
OS by JJsir

Pass Parameters to a Function

 You can define a function that will accept parameters while calling
the function.
 These parameters would be represented by $1, $2 and so on.

 # Define your function here


 Hello ()
 {
 echo "Hello World $1 $2“
 }
 # Invoke your function

 Hello Rohit Sharma


OS by JJsir

Returning Values from Functions

 If you execute an exit command from inside a


function, its effect is not only to terminate execution
of the function but also of the shell program that
called the function.
 If you instead want to just terminate execution of the
function, then there is way to come out of a defined
function.
 Based on the situation you can return any value from
your function using the return command whose syntax
is as follows −
 return code
OS by JJsir

Returning Values from Functions Example

 # Define your function here


 Hello ()
 {
 echo "Hello World $1 $2"
 return 10
 }# Invoke your function
 Hello Zara Ali
 # Capture value returned by last command
 ret=$?
 echo "Return value is $ret"
OS by JJsir
Various shell script examples
(Que. for Practice Purpose)
 While Loop  Make directory by checking existence
 For Loop  Read a file
 Get User Input  Delete a File
 If statement  Append to file
 Else if and else condition  Test if File Exists
 Case Condition  Send Email Example
 Get Arguments from Command Line  Get Parse Current Date
 Get arguments from command line with  Counting Vowels Of String
names  Factorial Of Number
 Combine two strings in a variable  Arm Strong Number
 Get Substring of Strings  Palindrome String
 Add 2 numbers into a variable  Prime Number
 Create a Function  Odd or Even Number
 Pass Return Value from Script  Upper to Lower String
 Make directory
OS by JJsir

SHREE H. J. DOSHI INFORMATION TECHNOLOGY INSTITUTE JAMNAGAR

OPERATING SYSTEMS
BY JJ SIR

CH-5 : GETTING STARTED WITH LINUX, LINUX BOOTING, LINUX ADMIN (UBUNTU)
OS by JJsir

Unix

 UNIX was earlier known to be UNICS, which stands


for UNiplexed Information Computing System..
 UNIX is a popular operating system, first got
released in 1969.
 UNIX is a multi-tasking, powerful, multi-user, a
virtual OS which could be implemented on a variety
of platforms(Eg. Desktops, Laptops, Servers, and
mobile devices, etc).
OS by JJsir

History

 The development of UNIX system got started at Bell


Labs by the scientists, Ken Thompson, Dennis
Ritchie and various others.
 The first version of this operating system was written in
assembly language, but later during 1973, Version 4
was written in C language.
 During the 1990s, the UNIX system started gaining
popularity as the Linux distributions were developed by
several programmers.
 In 2000, Apple released its own UNIX system, known as
Darwin, which later became MacOS.
OS by JJsir

Characteristics of UNIX

 Portability: The UNIX system is written in HLL which makes it easier


to understand, modify and transport it to other machines. This
feature of UNIX operating system helps the user to change and
compile the code on a new machine.
 Multi-tasking: UNIX supports more than one process to run at a time
i.e., if a process is running, then other processes can also be run in
the background.
 Pipes and Filters: UNIX contains pipes and filters which help in
making of complex programs from simpler programs.
 Shell :UNIX has a simple interface which helps the user to perform
various functions. The shell hides the intricate hardware details from
the user.
 Extensive Library: The UNIX has a support of extensive library
which makes it a useful and relevant
OS by JJsir

Advantages of UNIX

 The main advantage of Unix is its portability which


helps the user to run the program on different machines.
 UNIX makes minimum use of physical memory usage
while running the various tasks flawlessly.
 UNIX is capable to perform complex tasks with the
minimal load and efficiently.
 It supports Hierarchical File system which helps for easy
maintenance and efficiency.
 UNIX system is secure due to its strong server validation
and authentication.
OS by JJsir

Disadvantages of UNIX

 UNIX operating system is command line based


which increases the difficulty for the casual users to
use it. It is meant for expert programmers who know
command line commands very well.
 Documentation of various UNIX tools is hard to find.
 The commands used are cryptic, makes use of
special characters which makes it difficult for new
users to handle.
OS by JJsir

Before Linux

 In 80’s, Microsoft’s DOS was the dominated OS


for PC
 Apple MAC was better, but expensive
 UNIX was much better, but much, much more
expensive. Only for minicomputer for
commercial applications
 People was looking for a UNIX based system,
which is cheaper and can run on PC
 Both DOS, MAC and UNIX were proprietary,
i.e., the source code of their kernel is protected
 No modification is possible without paying high
license fees
OS by JJsir

GNU project

 Established in 1984 by Richard Stallman, who believes that


software should be free from restrictions against copying or
modification in order to make better and efficient computer
programs
 GNU is a recursive acronym for “GNU's Not Unix”
 Aim at developing a complete Unix-like operating system
which is free for copying and modification
 Companies make their money by maintaining and
distributing the software, e.g. optimally packaging the
software with different tools (Redhat, Slackware,
Mandrake, SuSE, etc).
 Stallman built the first free GNU C Compiler in 1991. But
still, an OS was yet to be developed
OS by JJsir

Beginning of Linux

 A famous professor Andrew Tanenbaum


developed Minix, a simplified version of
UNIX that runs on PC
 Minix is for class teaching only. No
intention for commercial use
 In Sept 1991, Linus Torvalds, a second
year student of Computer Science at the
University of Helsinki, developed the
preliminary kernel of Linux, known as
Linux version 0.0.1
OS by JJsir

GNU, GPL Concept


OS by JJsir

Open Source & Freeware


OS by JJsir

Linux

 LINUX stands for Lovable Intellect Not Using XP.


 Linux was developed by Linus Torvalds and named
after him.
 Linux is an open-source and community-developed
operating system for computers, servers, mainframes,
mobile devices, and embedded devices.
 Linux receives requests from system programs and it
relays them into computer hardware.
 Linux is flexible, reliable, secure and it has large
community user’s support.
 Linux is compatible with almost every possible file
format and can run on a large number of devices.
OS by JJsir

Characteristics of Linux

 Linux can work on different types of hardware, so


Linux is portable.
 Linux is open source, so it is free to use and users can
also work on enhancing features of the Linux operating
system.
 It is multi-use operating system, that means multiple
users can access the system.
 Linux is secure as it provide password protection and
encryption of data.
 Linux is multi-programming as multiple application can
be run at same time.
OS by JJsir

Advantages of Linux

 Linux is compatible with large number of file


format.
 Linux is free of cost so it is easily available for users
to download and use.
 It is enhancing day by day as users can make
changes in the Linux operating system.
 Linux system rarely crashes as they are very stable.
 Linux does not collect much user data, so it ensures
privacy of user.
OS by JJsir

Disadvantages of Linux

 Linux does not provide some hardware drivers


which is drawback of Linux.
 Command line interface of Linux is difficult to use
for beginners.
 Some graphic tools are not available for Linux
operating system.
 Linux does not have standard versions, which makes
difficult for users to choose best version for their
needs.
OS by JJsir

Structure of linux

 1. Kernel:
 Kernel is the main core component if Linux, it controls the activity of
other hardware components. It visualizes the common hardware resources and
provide each process with necessary virtual resources. It makes the process to wait
in the ready queue and execute in consequently to avoid any kind of conflict.
 2. System Library:
 System libraries are some predefined functions by using which any application
programs or system utilities can access kernel’s features. These libraries are the
foundation upon which any software can be built.
 3. Shell:
 Shell can be determined as the interface to the kernel, which hides the internal execution of functions of kernel from the user.
Users can just enter the commend and using the kernel’s function that specific task is performed accordingly.
 4. Hardware Layer:
 Hardware layer of Linux is the lowest level of operating system track. It is plays a vital role in managing all the hardware
components. It includes device drivers, kernel functions, memory management, CPU control, and I/O operations. This layer
generalizes hard complexity, by providing an interface for software by assuring proper functionality of all the components.
 5. System utility:
 System utilities are the commend line tools that preforms various tasks provided by user to make system management and
administration better. These utilities enables user to perform different tasks, such as file management, system monitoring,
network configuration, user management etc.
OS by JJsir

Feature of linux

 Key features of Linux Operating System:



Following are the key features of the Linux operating
system:
 Multitasking: several programs running at the same time.
 Multiuser: several users on the same machine at the same
time (and no two-user licenses!).
 Multiplatform: runs on many different CPUs, not just Intel.
 Multiprocessor/multithreading: it has native kernel support
for multiple independent threads of control within a single
process memory space.
OS by JJsir

Installation and Configuration of Linux

 Step 1 – Boot from the CD-ROM


 Installation of UBUNTU requires an installation (bootable) CDROM.
 To make CDROM as first boot device.
 When computer boots up it shows the options to enter the BIOS Setup. Generally, F2
or delete key is pressed to enter the CMOS (BIOS) setup.
 As CDROM is the first boot device, the computer will first boot from the CDROM and
it would find the installation CD in the CDROM, and it will ask the user whether
computer should be booted using CDROM. Press enters when it is asked to boot from
CDROM.
 The installation process starts, and it initially greets the user with a welcome screen.
For default installation, press Enter and for server version type server and press
enter.
 Step 2 – Selection of Language
 Ubuntu supports many languages, and this step in the installation is to select one of
the languages from the given list. The default language is English.
OS by JJsir

Installation and Configuration of Linux


 Step 3 – Keyboard Layout
 Next, it asks to configure the keyboard layout. Generally, it will be automatically
 selected, so you can press Enter to ensure the selection. “Test your keyboard” option
 allows checking whether it is properly configured.
 Step 4 – Hardware and Networking Auto Discovery Next, Ubuntu configure your hardware
and network connection at this stage.
 If there is any network related error then we have option for “Do not configure the network at
this time”, so installation will not be interrupted due to this error.
 Step 5 – Set a Hostname
 Installation asks for setting a host name for the computer.
 Step 6 – Partition the Disk
 Partition has four option:
 1. Resize IDEI master (IDE) and use free space
 2. Erase entire disk: IDE Master
 3. Erase entire disk using LVM
 4. Use target continuous free space
OS by JJsir

Installation and Configuration of Linux

 Step 7 – Wait during Automated package copying


 Step 8 – Set the Time Zone (Depending on your location, set the time zone for your locality.)
 Step 9 – Set your Real Name, Username and Password To login to the system, users require
username and password, which needs to be unique.
 Step 10 – Install the GRUB Boot Loader (If windows is also installed on the same hard disk as
Ubuntu, It will verify that GRUB boot loader is to be installed.)
 The GRUB boot loader displays the list of operating systems installed on the computer when
computer starts booting.
 Step 11 – Reboot for the Second Installation Phase
 Step 12 – Wait During Package Installation
 Step 13 – Configure your Monitor
 After package are installed, set the resolution for monitor
 Step 14 – Boot for the first time
 After rebooting it display the Ubuntu login screen, where user can enter the password and enter
the system.
OS by JJsir

Startup, Shutdown and boot loaders of Linux

 Shutdown:
 If you are going to initiate a shutdown of your system
and there are other users logged in to your system, it is
always polite to notify them first.
 To do this, we would use the shutdown command. The
shutdown command will accept times and a broadcast
message:
 shutdown [options] time [warning_message]
 shutdown and reboot immediately
 $ shutdown -r now
OS by JJsir

Startup, Shutdown and boot loaders of Linux

 Linux's boot process


 The Linux boot process is the name given to the startup procedures/order that your
system goes through to load its operating system.
 In the following example, I will be referring to booting Linux on x86 architecture
 Boot Loader
 The Ubuntu installation routine writes a new boot sector (also known as boot loader).
 The boot loader is a separate program called GRUB (Grand Unified Boot Loader).
 If more than one operating system is installed, GRUB boot loader with list of all
installed operating system appears.
 The first option will be selected automatically within 10 seconds.
 In the boot loader screen, all pre-installed operating systems are listed, apart from
that an entry ending in “(recovery mode)”.
 This is a safe mode within windows, in that the system boots with safe system settings.
OS by JJsir

Linux Booting Process

 1. BIOS
 BIOS stands for Basic Input/Output System
 Performs some system integrity checks
 Searches, loads, and executes the boot loader program.
 It looks for boot loader in floppy, cd-rom, or hard drive. You can press a key (typically F12 of F2, but it
depends on your system) during the BIOS startup to change the boot sequence.
 Once the boot loader program is detected and loaded into the memory, BIOS gives the control to it.
 So, in simple terms BIOS loads and executes the MBR boot loader.
 2. MBR
 MBR stands for Master Boot Record.
 It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
 MBR is less than 512 bytes in size. This has three components 1) primary boot loader info in 1st 446 bytes 2)
partition table info in next 64 bytes 3) mbr validation check in last 2 bytes.
 It contains information about GRUB (or LILO in old systems).
 So, in simple terms MBR loads and executes the GRUB boot loader.
OS by JJsir

Linux Booting Process

 3. GRUB
 GRUB stands for Grand Unified Bootloader.
 If you have multiple kernel images installed on your system, you can choose which one to
be executed.
 GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it loads
the default kernel image as specified in the grub configuration file.
 GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t understand
filesystem).
 Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The
following is sample grub.conf of CentOS.
 4. Kernel
 Mounts the root file system as specified in the “root=” in grub.conf
 Kernel executes the /sbin/init program
 Since init was the 1st program to be executed by Linux Kernel, it has the process id (PID) of
1. Do a ‘ps -ef | grep init’ and check the pid.
 initrd stands for Initial RAM Disk.
 initrd is used by kernel as temporary root file system until kernel is booted and the real
root file system is mounted. It also contains necessary drivers compiled inside, which helps it
to access the hard drive partitions, and other hardware.
OS by JJsir

Linux Booting Process

 5. Init
 Looks at the /etc/inittab file to decide the Linux run level.
 Following are the available run levels
 0 – halt
 1 – Single user mode
 2 – Multiuser, without NFS
 3 – Full multiuser mode
 4 – unused
 5 – X11
 6 – reboot
 Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate program.
 6. Runlevel programs
 When the Linux system is booting up, you might see various services getting started. For example, it might say “starting sendmail ….
OK”. Those are the runlevel programs, executed from the run level directory as defined by your run level.
 Depending on your default init level setting, the system will execute the programs from one of the following directories.
 Run level 0 – /etc/rc.d/rc0.d/
 Run level 1 – /etc/rc.d/rc1.d/
 Run level 2 – /etc/rc.d/rc2.d/
 Run level 3 – /etc/rc.d/rc3.d/
 Run level 4 – /etc/rc.d/rc4.d/
 Run level 5 – /etc/rc.d/rc5.d/
 Run level 6 – /etc/rc.d/rc6.d/
 Please note that there are also symbolic links available for these directory under /etc directly. So, /etc/rc0.d is linked to
/etc/rc.d/rc0.d.
OS by JJsir

LILO Configuration

 LILO (LInux LOader) is a boot loader for use with the Linux operating system.
 Most new computers are shipped with boot loaders for some version of
Microsoft Windows or the Mac OS.
 If a computer is to be used with Linux, a special boot loader must be installed.
 LILO is the most popular boot loader among users who employ Linux as their main,
or only, operating system.
 When a computer is powered-up or restarted with LILO installed in the usual
manner, the basic input/output system (BIOS) performs some initial tests and then
transfers control to the Master Boot Record (MBR) where LILO resides.
 The primary advantage of LILO is the fact that it allows for fast boot up of Linux
when installed in the MBR.
 Its main limitation is the fact that not all computers tolerate modification of the MBR.
 In these situations, there are alternative approaches for using LILO, but it takes
longer.
OS by JJsir

GRUB configuration

• GRUB (GRand Unified Bootloader)

 GNU GRUB is a bootloader capable of loading a variety of free and proprietary


operating systems.
 GRUB will work well with Linux, DOS, Windows, or other os.
 GRUB stands for GRand Unified Bootloader.
 GRUB is dynamically configurable, This means that the user can make changes
during the boot time, which include altering existing boot entries, adding new,
custom entries, selecting different kernels, or modifying initrd.
 GRUB also supports Logical Block Addressmode. This means that if your computer
has a fairly modern BIOS that can access more than 8GB (first 1024 cylinders) of
hard disk space, GRUB will automatically be able to access all of it.
 GRUB can be run from or be installed to any device (floppy disk, hard disk, CD-
ROM, USB drive, network drive) and can load operating systems from just as many
locations, including network drives. It can also decompress operating system images
before booting them.
OS by JJsir

Which one is better LILO or GRUB?

 LILO supports only up to 16 different boot


selections; GRUB supports an unlimited number of
boot entries.
 LILO cannot boot from network; GRUB can.
 LILO must be written again every time you change
the configuration file; GRUB does not.
 LILO does not have an interactive command
interface.
OS by JJsir

LILO V/s GRUB

LILO GRUB

LILO has no interactive command interface GRUB has interactive command interface

LILO does not support booting from a network GRUB does support booting from a network

If you change your LILO config file, you have to GRUB automatically detects any change in
rewrite the LILO stage one boot loader to the config file and auto loads the OS
MBR

LILO supports only linux operating system GRUB supports large number of OS

LILO supports only up to 16 different boot GRUB supports an unlimited number of boot
selections entries.
OS by JJsir

Creating Linux User Account and Password

 To create a new user in Linux, use the adduser command. The following is the syntax
to create.
 sudo adduser newusername
 The sudo is a program for computer operating system such as Linux, Linux that
 allows users to run programs with the security privileges of another user, by default
the Superuser.
 The name is combination of “Do as Su” where “Su” is for “Super user”.
 After typing that command following process started by Linux:
 Type and confirm password.
 Enter in the user’s information. This is optional. Press enter key to automatically fill
the field with the default information.
 Press Y (or Enter key) when asked to confirm the information.
 You have just added a new user to your Ubuntu operating system.
OS by JJsir

Installing and Managing Samba Server

 What is samba server ?


 Samba server is software in linux for communicate with
other Operating System in network
 What is it use ?
 Samba server mostly use to share document and
hardware with linux and other OS like window
 You can share file from window OS and also share from
linux to window OS
OS by JJsir

Steps for Installing Samba Server


 If you want to share files between your Ubuntu and Windows computers, the best option is the
Samba.
 Download latest version of samba from the site: https://www.samba.org/samba/ftp/samba-
latest.tar.gz
 To install, first open a terminal window and enter the following command:
 sudo apt-get install samba smbfs
 After the successful execution of this command, the Samba will get installed, now you must
configure it to make it accessible.
 To configure it, open the configuration file using the following command in an editor:
 sudo gedit /etc/samba/smb.conf
 Find the following section in the file:
 # security = user
 Remove the comment before the security line and add the following line just below it:
 security = user
 username map = /etc/samba/smbusers
 This will set Samba to use the smbusers file for looking up the user list
OS by JJsir

Installing and Managing Apache Server


 The Apache Web Server is one of the most popular open-source HTTP servers. It is powerful, secure, and fully
featured web server.
 Installing Apache HTTP Web Server
 First, you should have the Apache server downloaded or download the Apache Server for Linux.
 Now extract the Apache Files by following commands:
 gunzip -d httpd-2_0_NN.tar.gz
 tar xvf httpd-2_0_NN.tar
 To install Apache server on Ubuntu, use following commands:
 sudo apt-get update
 sudo apt-get install apache2
 The Apache server is installed. To check if Apache is installed, go to your browser, enter your server’s IP address.
 The page should display the message: “It Works!”
 Managing Apache Server
 You must understand the main configuration files of Apache which can be found in the “/etc/apache2” folder.
 You can explore this folder by following command:
 cd /etc/apache2
 ls
OS by JJsir

LDAP Services

 LDAP stands for


 Lightweight Directory Access Protocol
 LDAP not only keeps a list of users, but you can also use
it as storage for your files.
 You can use it for authenticating users.
 Also, you can store DNS records in the LDAP server.
 Another usage for LDAP, you can use it as a yellow
pages directory service for an organization to provide
information about users or employees, departments,
contact information, phone numbers, addresses, private
data, or whatever.
OS by JJsir

DNS Services

 Domain Name System


 The purpose of DNS is to translate a domain name
into the appropriate IP address.
 This is done by looking up the dns records of the
requested domain.
 There are typically eight steps in this DNS lookup
process that follow the information path from the
originating web browser to the DNS server and
back again.
OS by JJsir

FTP Services

 FTP (File Transfer Protocol) is a standard network


protocol used to transfer files to and from a remote
network.
 There are several open-source FTP servers available for
Linux.
 The most known and widely used vsftpd.
 vsftpd (Very Secure Ftp Daemon), a stable, secure,
and fast FTP server.
 Installing vsftpd on Ubuntu 20.04
 sudo apt install vsftpd
OS by JJsir

Web Services

 Apache is a powerful and capable web server.


 To make initial setup as easy as possible, this makes it a great choice for new projects when
you need to be productive quickly.
 Here are the few steps to optimize the web service performance of Apache Web Server.
 Unload Unneeded Modules
 In Ubuntu based system, you will see a folder called /etc/apache2/mods-enabled and
/etc/apache2/mods-available/.
 The mods-available folder is a list of all the modules installed on a particular server.
 You should disable following modules if you do not need them:
 PHP
 SSL
 Rewrite
 Perl
 Python
 Rack / Ruby / Passenger
OS by JJsir

Configure Ubuntu's Built-In Firewall

 Firewall is considered as the first method of defense in securing your cloud server.
 Ubuntu includes its own (built-in) Firewall known as UFW.
 UFW stands for “Uncomplicated Firewall”.
 Its main goal is to provide an easy-to use interface.
 The firewall is disabled by default. To enable the firewall, run the following commands from a
terminal. sudo ufw enable
 To install Firewall: sudo aptitude install ufw Or sudo apt-get install ufw
 To check the status, use following command: sudoufw status
 Setup rules
 You should first define some rules for the firewall for allowing and denying connection.
 To set the defaults used by UFW, use the following commands sudo ufw default deny
incoming And sudo ufw default allow outgoing.
 If you want to deny the outgoing request also, use the following command: sudo ufw default
deny outgoing.
 Enable the SSH connection, use this command: sudo ufw allow ssh
OS by JJsir

Working with wine

 Wine (originally an acronym for "Wine Is Not an


Emulator") is a compatibility layer capable of
running Windows applications on several operating
systems, such as Linux, macOS.
 Instead of installing internal Windows logic like a
virtual machine or emulator, Wine translates
Windows API calls into POSIX calls on-the-fly,
eliminating the performance and memory penalties
of other methods and allowing you to cleanly
integrate Windows applications into your desktop.
OS by JJsir

SHREE H. J. DOSHI INFORMATION TECHNOLOGY INSTITUTE JAMNAGAR

OPERATING SYSTEMS
BY JJ SIR
BEST OF LUCK FOR EXAM

CREATED BY :- DIGRAJSINHSOLANKI.COM

You might also like