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

Os Material

The document provides an introduction to operating systems with the following key points: 1) An operating system is a software that manages computer hardware resources and provides common services for computer programs. It acts as an interface between the user and hardware. 2) Operating systems perform functions like memory management, CPU management, disk management, input/output management, and security management. 3) There are different types of operating systems including batch, multiprogramming, multiprocessing, time-sharing, online, and real-time operating systems. Each type has distinct characteristics in how they allocate resources and handle multiple programs and users.

Uploaded by

Raj
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)
114 views

Os Material

The document provides an introduction to operating systems with the following key points: 1) An operating system is a software that manages computer hardware resources and provides common services for computer programs. It acts as an interface between the user and hardware. 2) Operating systems perform functions like memory management, CPU management, disk management, input/output management, and security management. 3) There are different types of operating systems including batch, multiprogramming, multiprocessing, time-sharing, online, and real-time operating systems. Each type has distinct characteristics in how they allocate resources and handle multiple programs and users.

Uploaded by

Raj
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/ 89

Chapter : 1 OPERATING SYSTEM

 Introduction of Operating System : -

 Operating System is commonly abbreviated as OS or O/S and is responsible for management


and co-ordination of activities & shairing of resources of computer.
 Operating System is a system s/w which acts as a interface between user & h/w.
 It is one of the essential component of computer system.
 Almost all computer including handheld computers,desktop computers,supercomputer and even
video game console use an Operating System.
 Opreating System is a large collection of programs, which manage resource of computer system
such as (memory, processor, file system, Input/Output devices)
 OS offers number of services to application program and users.Application accsess these
services through APIs (Application Program Interface)
 By invoking these interface,the application can request a service from the OS,pass parameter
and receive the result of operation.
 User may also interact with OS with some kind of software User Interface (UI)like typing
commands by using Command Line Interface (CLI) or Graphical User Interface (GUI).
 For Handheld and Desktop Computer User Interface (UI) is the part of OS and large multiuser
system like Unix and Unix like OS, UI is used as an application.
 Operating System keep track over status of each resource & decide who will have a control
over computer resource.
 Primary Objectives of Operating System is to make computer system convenient to use and
utilize computer hardware in an efficient manner.
 We can easily understand the concept of OS with simple diagram.
 Accoring to figure, the OS directly controls computer H/W resources.
 Other program rely on facilities provided by OS to gain access to computer system
resources.
 There are two ways for interaction with Operating System.
1)By means of OS call in profram.
2)Directly by means of OS commands.

 By means of OS System Call:-


System calls provides the interface to a running program & the OS.User
program receives OS services through the set of system calls.Now a days these calls are
supported by High level Languages like Pascal,C etc which replaces Assembly Level
Languages for system Programming.Use of System Call in C or Pascal program is very
much resemble predefined function or Subroutine call.

 Direct by means of OS commands:-


Instead of System call user may interact with OS directly by means of OS
Commands.
Example:-If you want to display the current date in MS-DOS,you simply type the
date in command prompt to display the current date.

 Functions of Operating System : -

 Memory Management :-
 When you start a program, OS retrieves it from permanent disk & loads into main
memory (RAM).
 Before loading OS checks whether enough memory space is there or not i.e. two parts :
1. Memory allocation
2. Memory deallocation

1)Memory Allocation:
Memory allocation is the act of managing computer memory. In its simpler
forms, this involves providing ways to allocate portions of memory to programs at their request,

2) Memory Deallocation:

Freeing memory for reuse when no longer needed. The management of main
memory is critical to the computer system.

 CPU Management :-
 OS helps CPU to schedule its activities so as to meet demand of various part of
computer because CPU is needed by more than one program / resource.

 Disk Management :-
 It Manages the secondary storage devices
 OS helps to store & retrieve file whenever required.
 User need not to bother about how & where data or files are stored & how to find them.

 Input / Output Management :-


 OS manage the communication between various Input and output devices to perform the
various functions of computer i,e it controls all Input and Output devices and take
measures which would ensure that data is transmitted efficiently and correctly to and
from I/O devices.

 User Interface :-
 Gap between machine language and human readable language is solve with the help of
OS.
 creates an easy & interactive interface between user and computer using command
interpreter.
 Command Interpreter helps user to interact with Operating System.
 Security Management:-
 It ensure data security and integrity.
 It keeps different data and program in memory in such a manner that it do not
interface with each other.

 Processor Management:-
 OS assign processor to different task that must be performed by computer
system.whenever OS find the processor idle it assign job to the processor.
 The main feature of processor management is that to ensure that program or
a process is run on each processor at all time.

 Various Types of OS

 There are different types of Operating Systems they are as follows :-

1.Batch Operating System.


2.Multiprogramming Operating System.
3.Multiprocessor Operating System.
4.Time Sharing Operating System.
5.Online Operating System.
6.Real time Operating System.
 Batch processing OS
 Batch operating system is also kmown as serial, sequential offline,or stcked job processing
OS.
 In this types of Os computer operator collects the program,which have been punched on
card and stack one program or job on top of another.

 when batch of program have been collected, operator load this batch of program
into computer.

 Each job is executed one after another


 Finally operator fetch or retrive the printed output.

 Scheduling of batch system is very simple.


 Execution is done by FCFS (first come first serve) form.
 Memory management in batch operating system is also simple.
 Useful in preparation of customer statement where it is not necessary to update information
on daily basis.

 ADVANTAGES :-
 After I/p process is over, while processing is going on user can attend other jobs.
 This Operating System is less complicated.

 DISADVANTAGES :-
 Difficult to provide priority Scheduling.
 Turn around time is very long.
 Access to one program is not possible.
 It is not convenient for program development.
 If result of particular program or time detail are required,you have to wait till entire
batch is processed.

 Multiprogramming Operating System :-

 OS which handles more than one program in main memory at a time is known as
Multiprogramming OS.
 In fig.

Supervisor
Waiting Prog A
Prog B
O/P Data Prog C
(waiting for
CPU)

Secondary Disk Storage CPU


 2 or more program are reside in main memory & execute them concurrently.
The CPU switches from one program to another immediately.

 The main advantage of this Operating system is CPU can allocate time to several programs
instead of remaining idle when one program is busy with I/O Operations.

 Possible for several users to share the time of CPU.

 In this Operating system all program appear to be processed simultaneously but actually each
program get turn for executing I,e at any time only one of the program has control of CPU and
executing the instruction.

 ADVANTAGES :-
 Many programs can run simultaneously.
 Time is not wasted in switching from one program to another.
 Maximum utilization of resources.
 Important & short jobs need not wait for batch.

 DISADVANTAGES :-
 OS is complicated because many program are handled together.
 Job of resource management & memory management increases.
 Large main memory required.

 Multiprocessor System :-
 The Multiprocessor Operating system is called Multiprocessor because it make use of more
than one CPU.
 the term multiprocessor is computer with 2 or more CPU‟s that have ability to simultaneously
execute several programs.
 In this Operating System different program can process at the same time by different CPU.
 In case of failures of one CPU, the other takes over complete workload until repair are made.
 There are more than one program in main memory at a time.
 The basic organization of typical multiprocessing system is shown in fig given below:
CPU 1 Main Mem. CPU 2

I/O Proc I/O Proc

I/O Units I/O Units

 Instead of one CPU,computer has two or more CPUs I,e more than one program is executed in
Operating system at a time.
 This is needed when maximum program running on your computer are likely to need CPU.

 ADVANTAGES :-
 Improve the performance by allowing parallel processing of programs.
 Turnaround time of this system is less.
 In case of failure of one CPU other CPU can take over the total workload without
any loss. .
 More efficient utilization of CPU & other devices of computer.

 DISADVANTAGES :-
 OS is more complicated because multiple program and processor are handled
together.
 A large main memory required.
 It is very expensive.

 Time Sharing OS :-

 It is a form of multiprogramed OS which operates in an interactive mode with quick response


time.
 A time shairing Operating System allows number of user to use computer.
FIGURE:- User 6 User 6
Ready User 1 Ready User 1
Wait Wait

User 5 User 2 User 5 User 2


CPU CPU
Ready Active Active Ready

User 3 User 3
User 4 User 4
Wait Wait
Wait Wait

 The main objectives of time shairing OS provide fast response time to each user of computer.
 In this OS CPU is divided into user on a schedule basis.
 It allows all user program to gets a brief share of CPU in turn.
 Each user program,starting from first till last user has allocated a short period of CPU time to
all users.
 A short period of time during which user can get attention of the CPU is known as „a time slice‟
or „time slot‟ and it is in order of 10 to 100 milliseconds.
 In this OS,only one program can be in the control of CPU at given time like Multiprogramming
OS.
 It is not possible to keep progam of all user simultaneously in main memory because of limited
main memory.
 The time shairing Operating System keeps only few programs in main memory and rest of the
program are stored on disk storage.
 Main features of Time shairing OS are as follows:
1) Processing time are divided into various program called time slice.
2) Each program is given the CPU time one by one.
3) Shairing of only one CPU by different user simultaneously.

 ADVANTAGES :-
 Turn around time is negligible.
 Computing cost is very less.
 All programs get equal attention & small program get over fast.
 Reduce CPU idle time.
 Avoids duplication of s/w.
 DISADVANTAGES :-
 OS is more complicated.
 Question of security: Hundred of users are using the system simultaneously so
provision of security is provided.
 Problem of Data Communication:In this system user communicate with main
computer through remote terminals that requires data communication facilities.

 Online Processing System :-


 This Operating system is also called as direct access or random access.
 The important feature is to get immediate & direct access to record.
 In online system, the terminal used by operator is connected to main computer, so that operator
can interact with computer in conversational mode.
 This OS is used in application requiring fast response from the computer.
 Eg - Airline Reservation System.

 ADVANTAGES :-
 Turn around time is negligible.
 Access & retrieval of record is quick direct.

 DISADVANTAGES :-
 OS is complicated & costly.
 Question of security.
 Data transmission facility required.
 i.e. in OS user interact with main computer system through remote terminal
that require data comm. facilities.
 Real Time Processing :-

 A system in which a transaction access & updates a file quickly enough to affect the original
decision-making is called Real time system.
 This Operating System is used where immediate response from computer requires.
Eg – stock market.
 Real time use online processing but online system need not operate in real time mode.
 Real time OS should be highly reliable because a small problem can be lead into fatal accident
and to achieve reliability, Real time OS should be duplicated so that,at the time of breakdown
,backup facilities are immediately for continious operation of system.

 ADVANTAGES :-
 Response time is very less.
 Data processing is very fast.

 DISADVANTAGES :-
 A complicated system.
 Very expensive.

 APPLICATIONS :-
 Air traffic control system.
 In Chemical process control system
 In Control satellite operation.
Chapter : 2 PROCESS
 Introduction to Process :-

 Process is nothing but it is a program in execution i,e it can be defined as a program currently
making use of processor at any time.
 Execution of user program in Multiprogramming or Time Shairing System is represented by set
of processes.
 Interaction between process involves Shairing or Exchanging data or messages and control
signals.
 Process is made up of a tuple
 Tuple consist of process id, code, data, register value, PC value where,
1) process id is unique id in system which is assign to process.
2) Code is a program code.
3) Data is data used during its execution i.e. initialization & un-initialization.
4) Register values is value in machine registers.
5) PC is address in program counter i.e. starting address of program.
 At the moment only one process is actively executing which is given to CPU.
 Other process are in 2 state of suspension, when interrupt arise, the process executing on CPU
is suspended.
 After interrupt is processed, OS instruct the scheduler, which select one process for execution
on CPU.
 Note that process is sequential in nature i,e instruction in program code is executed one after
another.
 Example:- Following process exist in an OS.
Process P1: (P1,C1,D1,rv1,Pc1)
P2: (P2,C2,D2,rv2,Pc2)
P1: (P3,C1,D3,rv3,Pc3)

 Process P1 and P3 represent different execution of same program,while P2 represent execution


of another program.
 P1 and P3 could be identical in all componenet other than Process id.OS differentiate them by
their identities.
 Process Creation :-
 OS creates a user process to represent the execution of user program.
 This is done when a user type a name of program to be executed.
 Alternatively a user process may be explicitly created by another user process through system
call.
 A System process may be created by OS for its own purpose.
Eg:-to service a request made by user.
 Following actions for creating a new process.
 Create a Process Control block (PCB) for process.
 Assign a process id & priority.
 Allocate memory & register resource to process.
 Set up process environment.
 Initialize resource accounting information for process.

 Process State :-
 Process state is used by OS to simplify process scheduling.
 Process Pi is said to be in state Si. The four fundamental state for process are.

 Running State :-
 A CPU is currently allocated to process & process is in execution.
 Blocked State :-
 A process is waiting for a request to be satisfied, i.e. process cannot
execute even if CPU is available.
 Ready State :-
 The process is not running however it can execute if a CPU is
allocated to it (i.e. process is not blocked)
 Terminated State :-
 The process has finished its execution.
 A state transition is a change from one state to another.
 Process state is change by occurrence of some event in system.
Fig:
Terminate
Running

Ready Blocked

 When a process is in a running state makes a request of I/O it has to enter the block state
waiting till completion of I/O
 After completion of I/O, process state changes from blocked to ready.
 A ready process becomes running when CPU is allocated to it.
 OS maintains a list of process in ready state. This list is called the Processed Scheduling list.
 The scheduler picks one process from list & allocates CPU to it.
 Note that the state of process is the function of two component.
1. Recent behaviour of process.
2. Occurrence of event pertaining to it.

 Example:- state of process indicates wheather the process made a request


recently & wheather the request is been satisfied. It makes possible to design
the function of process scheduler arount the state of process existing in
system.
This can be done as follows-OS maintains the list of process in ready state
that is called as Process Schedular List. Schedular picks one process from
list and allocate a CPU to it.

 Process Control Block (PCB) :-


 A process is simply a program in execution.OS consider process to be fundamental for resource
allocation.Following resources are allocated to the process:
1. Memory
2. Secondary memory i,e swap space.
3. I/O devices
4. File opened by the process.
5. CPU time consumed by process.
 A data structure, called the process control block, is used by OS to keep track of all information
related to process.
 PCB contains following information

 Process id
 Priority
 Process state
 PSR (Process state
Register)
 Registers
 Event Information
 Memory Allocation
 Resources held
 PCB Pointer

 Process Scheduling information


 consist of 3 states (fields) process id, priority & process state
 Process Status Register (PSR) & Machine Register
 holds content of PSR & register when execution of process is suspended.
 Event Information
 when process is in blocked state, this field contains information concerning the event for
which process is waiting.
 Memory & Resource Information
 Memory & resources information are useful for deallocating memory & resources when
process terminates.
 PCB pointer
 pointer to next PCB in process scheduling.

 The PSR and Machine register field represent a snapshot of CPU when it is released by the
process.
 When a process is scheduled once again yhis information from its PCB can simply be loaded
into processor to resume its execution.
 Event information field of PCB plays an important role in effecting appropriate state transition
in system.

 Process Scheduling :-
 Process Scheduling is impotant feature of OS which determine which request should be
service.
 It is fundamental OS function which involves following task:
1. Creating new process.
2. Monitoring process status.
3. Selecting process for execution (Process Scheduling).
4. Allocating CPU to selected process (Process Dispatcher).
5. Deallocating CPU from process and determine new state of process (Process
preemption)
6. Termination of process.
7. Supporting communication and synchronization request of process.
8. Interfacing with other OS modules which affect process state.
 Almost all computer resources are schedule before use.
 The process scheduling component consist of 3 smaller component.
1. Event handler.
2. Process Schedular.
3. Process Dispatcher.

 Fig:-
Command interpreter job handler event handler process dispatcher
PCB

JCB List PCB List

Job scheduler
Process schedular
 Process scheduler examines the information in PCBs to select a process for execution
and hands over its PCB to dispatcher. The dispatcher loads the PSR and register
contents from PCB into CPU to initiates execution of process.
 Event handler process each interrupt occurring in system,determines the event causing
the interrupt and logs an application change of state in PCB of affected process.

 SCHEDULING:-

 Scheduling policy specify criteria for service request.


 Scheduling is important because it influences user services and efficiency of CPU
utilization.
 There are 4 event related to Scheduling.
1. Arrival.
2. Scheduling.
3. Preemption
4. Completion
 Arrival:-
When user submit request to OS then request arrives in the system.when request
arrives,the system takes note of its arrival time and other characteristic like kind
and quantum of request etc
This information is entered into list of pending requests.some information
associated with the request.
Eg:-elapsed time since arrival,may be updated as it await attention of server.
 Scheduling:-
A request is scheduled when the scheduler select it for servicing.The Scheduled
request is removed from list of pending request.
 Preemption:-
A request is preempted when the server switches to servicing of another request
before completing the request.A process is resumed when it is scheduled again.

 Completion:-
When a processing of request get completed Scheduling is performed to select
another request for processing.
 Fig:-
Preempted request

Arriving request
Scheduled

Server completed request

Pending request scheduler data flow


Control flow

 Figure shows movement of request in system:-


 All request waiting to be services are kept in list of pending requests.
 Whenever scheduler have to be performed,the scheduler examines the pending
request and select one for servicing.
 This request is handed over to the server.
 This request leaves the server when it is completes or it is preempted by the
scheduler in this case it put back into list of pending request.
 In either situation,scheduler performs scheduling to select the next request to be
serviced.
 Broken arrows can be drawn from scheduler to server and vice versa.
 There are different CPU scheduling Algorithms in operating system.
1) First Come First Serve (FCFS)
2) Shortest job next (SJN)
3) Round Robin
4) Priority base Non Preemptive
5) Priority base preemptive

1) First Come First Serve :-


- FCFS is the simplest CPU scheduling Algorithm in system.
- In this Scheduling the process come first is given service of CPU
- FCFS is managed with FIFO(First in First out) queue.
- The process which is in executing state is removed from queue
- when process enters the ready queue its PCB is linked to tail of queue, when CPU is
free it allocated the process at the head of queue.
- Main important feature of FCFS scheduling is process is executed sequentially
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 but it is the time required to complete the particular process.

Process Burst time

P1 24
P2 3
P3 3

- If process arrives in order P1, P2, P3 & served in FCFS manner as shown in Gantt
Chart.
P1 P2 P3

0 24 27 30
- The waiting time is 0 ms for P1
24 ms for P2
27 ms for P3

 Average waiting time (0 + 24 + 27)


3
= 17 ms

2) Shortest Job Scheduling (SJF) :-


- SJF scheduling is 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.
- Consider the following set of process with given time.
Process Burst time
P1 6
P2 8
P3 7
P4 3

- Using SJF scheduling user scheduled as follows :-


P4 P1 P3 P2
0 3 9 16 24

- The waiting time is 0 ms for P1


3 ms for P2
9 ms for P3
16 ms for P4

Average Waiting time is


= 3 + 9 + 16 + 24 = 7 ms
4
- Shortest job first scheduling is either preemptive or non preemptive
- Premptive algorithm is nothing but 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 algorithm is nothing but when a process arrives if at all the arrived
process has shortest burst time then also the current process is first executed.

3) Priority Scheduling :-
- In priority scheduling a priority is associated with each process & CPU is allocated
to the process with highest priority.
- A SJF algorithm is a priority algorithm where a large CPU burst, lower the priority.
- In priority scheduling priorities are generally from some fixed range of numbers
such as 0 to 7or 0 to 350.
- There is no arrangement on whether zero is highest or lowest priority.
- Some system use low no to represent low priority, other mayuse low number for
high priority.
- Consider the following, set of process. Assume that the arrival time is zero. Order is
P1, P2, P3, P4, P5 with the length of CPU burst time given in minutes.

Process Burst time Priority


P1 10 3
P2 1 1
P3 2 3
P4 1 4
P5 5 2

Assume that low represent the highest priority.

P2 P5 P1 P3 P4
0 1 6 16 18 19

- The waiting time is 0 ms for P1


1 ms for P2
6 ms for P3
16 ms for P4
18 ms for P5

- Average waiting time is


1 + 6 + 16 + 18 + 19

= 8.2 minutes
5
- Priorities can be defined either internal or external.
- Internal priorities use some measure to compute priority of process
Eg – time limits, memory requirements, number of open file & ratio of I/O
operation.
- External priorities are set by criteria that are external to OS such as importance of
the process etc.
- Can be either preemptive / non-preemptive when a process arrives at the ready
queue, its priority is compared with the priority of currently running process
(preemptive)
- Non-preemptive priority scheduling algorithm will simply put a new process at the
head of ready queue.
- Major drawback is in-definite blocking or starvation.

- A priority-scheduling algorithm can leave some low priority process waiting indefinitely for
CPU in highly loaded system.
- Solution of indefinite blocking of low priority is aging.
- Aging is a technique of gradually increasing the priority of processes that is waiting
for long time.

4) Round Robin Scheduling :-


- Round Robin scheduling is specially designed for time-sharing Operating system.
- It consist of small unit of time is called quantum or time slice.
- A time quantum is generally from 10 to 100 ms.
- A ready queue is arranged as circular queue.
- CPU scheduler goes around the ready queue allocating the CPU to each process for
particular time.
- To implement ROUND – ROBIN scheduling we keep the ready queue as FIFO
queue of process.
- CPU picks up 1st process from ready queue, set the timer & dispatch the process.
Eg – if process P1 – 10 minutes
P2 – 5 minutes
P3 – 15 minutes

- time quntum=4ms.
P1 P2 P3 P1 P2 P3 P1 P3 P3
0 4 8 12 16 17 21 23 27 30

- main advantage of this scheduling is the time quantum is given to each process and
process is terminated then the time quantum is given to next and so on and CPU time is
allocated to each process in circular manner.
- Performance depends upon size of time quantum.

 MULTIPROCESSING OS
- The operating system more than one processor (CPU) is multiprocessing OS, which shares
a computer bus, the clock & some time memory & peripheral devices.
- Advantage of multiprocessing Operating System is increase the throughput by increasing
the number of processor to get more work done in shorter period of time.
- Increase reliability i.e.If CPU fails then another CPU can take the total workload of failure
CPU.

 MULTITASKING OS
- Multitasking Operating System allows more than one job / task at the same time on a
computer.
- Operating System such as windows 9x, Unix, Linux, etc. support multitasking.
Eg – when you open MS Word & Internet Explorer at the same time Windows OS is doing
multitasking.
- There are two modes in multitasking, background & foreground.

 DIFFERENCE BETWEEN MULTIPROGRAMMING / MULTITASKING


- Multiprogramming is a concurrent execution of 2 or more program of same or different
users & also refers as concurrent processing.
- Multitasking is concurrent execution of multiple tasks.

 MULTITHREADING OS
 It is a technique in which process,execution and application is divided into threads that
can be run concurrently.
 Multithrading is useful for application that performs a number of essentially
independent task that do not need to be serialized.
 Multithreading computer have h/w support to efficiently execute ultiple threads.
 These are differentiate from multiprocessing system in that the threads must operate in
the same address space,as there is only one shared set of CPU cache and one Translation
Look aside buffer (TLB).
 Some critism of Multithreading Includes:
1. Multiple threads can interface with each other when shairing h/w
resources such as Cache ot Translation Look aside buffer (TLBs).
2. Execution time of single thread are not improved but can be degraded.
3. H/W technique use to support multithreading often parallel the s/w
technique used for computer multitasking of computer program.
Chapter : 3 MEMORY MANAGEMENT
Introduction:

 The memory hierarchy of a computer system consist of secondary memories like disks and
tapes,the primary memory (i,e RAM),and buffer or cache memories. Of these, management of
secondary memory is under the control of file system.
 OS responsibilities in memory management include memory allocation and memory
deallocation,efficient utilization of memory and protection of memory allocated to a program or
process from interference by other programs or process.
 Two types of memory management are performed during the operation of OS.These involves
memory allocation and deallocation.
1. to program or processes.
2. within a program or process.

 Allocation to user program and process is performed by the kernel. This activity is
characterized by the fact that the program and process sizes vary over a wide range of values.
This makes efficient utilization of memory rather difficult.
 Protection is very important issue in memory management as program and processes are
independent entities and have to be protected against mutual interferences.
 Memory management means identifying the free memory space & reusing the memory space
by making memory allocation, deallocation & effectively use of memory utilization.
 Memory management in operating system is management of the primary memory.
 Memory management in Operating System includes,

1) Efficient utilization of memory


2) Allocation of memory
3) Deallocation of memory
4) Protection of memory, allocated to a program of process from interference of
another process / program.
 There are 2 types of memory management :-
a) Contiguous memory management
- program & data instruction occupy a single contiguous memory

b) Non contiguous memory management


- program & data instruction in any occupy non contiguous memory.
- it consist of 3 important tasks
(a) Determine the amount of memory required to represent the value of data
item.
(b) Use of appropriate memory allocation model to implement the scope of
data item.
(c) Determine appropriate memory mapping to access the values non scalar
data item.

 CONTIGUOUS MEMORY ALLOCATION :-


- This approach uses the classical program model where each program is allocated single
contiguous area of memory.
- In contigious Memory allocation decision is made statically i.e. before the execution of
program begins.
- Practical issues in contiguous memory allocation are identified as :
1) protection of one program from another program
2) static allocation of program is execute from the allocated memory area
3) memory fragmentation & measures to over come it.
- Assume a single memory space to each process.

1) Memory protection
- Memory protection is used to avoid interference between program existing in
memory.
- Implementation of memory protection requires support from machine
architecture in the form of memory bound registers or memory protection keys.
Fig:

memory
protection violation Multiprogram
LBR interrupt supervisor
privilege mode 200k Job1 200 K
k
Job2 250K
PSR Job m
UBR 250 k

I)Memory Bound register


- Memory protection is done by memory bound register.
- When program is in execution of 2 special CPU register i.e. Upper Bound
Register (UBR) & (LBR) Lower Bound Register is used to ensure that it lies
within the allocated memory area.
- A memory protection violation interrupt is generated if an address lies outside
the allocated area.
- On sensing this interrupt, Os kernel can terminate program.

II)Memory protection keys


- Memory protection is based on protection keys.
- It is a small integer.
- The memory of system is conceptually divided into equal size called memory
blocks.
- When assigning a memory block to a program OS kernel assign a protection key
to memory block.
- Protection keys for all blocks are stored in separate memory called protection
key memory.
- Each program is assigned a unique protection key (APK) Authorized Protection
Key
- This authorizes the program to access any memory block whose protection key
matches its APK.
- The following points shows how kernel action are to implement memory
protection i.e.what kernel do for memory protection.
Fig:- protection
Key memory
MPI memory
CPU Supervisor 0K
50K
1 P1
1 1 Load 85,252
interrupt 1
80K
2
2 P2
=?

Address 85,252 P3

 According to figure During the execution of program its APK is put in the Memory Protection
Information (MPI) field of PSW.
 P1‟s APK is 1.Hence memory blocked allocated to P1 have memory protection key „1‟ and the
MPI field of PSW contains „1‟ when P1 is in execution.
 Consider an access to memory location with address 85,252. The memory protection h/w obtain
the protection key assign to memory block contains this address and compares it with values in
MPI. Since the values are different,a memory protection violation are raised.
a) Bound Register Scheme :-
i) While allocation of memory :-
- put the start of end address of memory area allocated to program
in the programs PCB.
ii) While dispatching :-
- Load PSR with content of relevant field of program PCB

b) Protection Key Scheme :-


i) While allocating memory :-
 Set a program‟s APK as a memory protection key for each
 memory block allocated to the program.
 Put the program‟s APK value into the program‟s PCB.
 While dispatching :-
 Load PSR with content of relevant fields of programs PCB.
2)Program relocation :-
 Linker binds a program to set of memory address starting on load
 origin of program.
 It makes program address sensitive i.e. the program can execute
 correctly only if memory area whose address (starting is equal to
 is load origin)
 To make a program to execute correctly at any other memory
 area, it has to be „relocated‟ by changing all memory address.
 This could be very expensive.
 Some system provides a special register in the CPU called
 relocation register.
 Every register used in program is relocated as follows
 Effective address = Address used by program + content of OS
 relocation register.
3)Memory fragmentation :-
 Memory fragmentation is defined as presence of unusable memory
area in computer system.
 External fragmentation – External fragmentation arises when free
memory area existing in a system is too small to be allocated to
program.
 Internal fragmentation – in Internal fragmentation memory
allocated to program is not fully utilized by address of operand.
 A computer system is said to use VM (Virtual Memory) if
 memory address use by instruction is different from effective address
of memory location access during its execution. i.e. VM is one that
make non contiguous memory allocation
 feasible memory handler in VM system is called the VM handler.
 While loading a program for execution it is viewed as sequential
 arrangement that are parts called program component.
 Each component is allocated a single CM.
 Area allocated to different components can be non contiguous
with one another.

 Logical & Physical address :-


1) Logical address is the address of instruction or data word use by program & obtain by
using index, base or seg. Register.
2) Physical address is effective address of an instruction or data.
Set of logical address use by program is logical space of program.
Set of physical address generated during operation is physical space of system.
These term is use to formulate a definition of virtual memory system.

 Virtual Memory System (VMS)

o Definition
It is a system where, in logical address of instruction or data word is different
from physical address.
- ATU (Address Translation Unit)in system is used to translate a logical address in
logical address space of program into physical address.
- 2 fundamental approach to implementation VM are
1) Paging
2) Segmentation
- These two approach differ from each other by boundaries & size of program.

 Virtual Memory Using Paging


1) Paging is a memory management technique, in which programmer‟s memory is non-
contiguous into physical memory.
2) In paged VM system, OS views the logical address space of program to be linear
arrangement of fix size component called pages.
- Each logical address used in program is considered as paid (Pi, Wi)
- Pi & Wi are number
Pi  page number
Wi  word number within Pi
- Pages in program & word in program are numbers from zero onwards.
- Consider a program P of size Z words & load origin of 0 it is a size of page in s words.
- The logical address space of P consist of pages 0, n-1 such that
Number of PS  n [z/s] page size / one page size
OR
n = [z/s]
where,
 [ ] – rounded integer quotient
 pages 0 to n-1 contains s word each, while the last page may contain less than s words.
 Logical address space of P consist of linear arrangement of logical address from (0,0) to
(n-1), z – (n-1) * (s-1)
- Physical memory of computer system consist of page block (page frames)
- Each holds exactly one page of program & each page block hold size of s words.
- At any time a page block may be free, or it may contain a page of some program.
- The size of page is chosen to be power of 2.
- This permits a logical address to be viewed as combining Pi & Wi.

 Address Translation Steps


- Logical address is viewed as pair (Pi, Wi)
- Pi is use to index the PMT.
- ID of memory block where Pi resides is obtained from block number field of PMt entry.
- Physical address is obtained by combining Pi & Wi.

Fig:-

Block Other
Memory ATU
MR NO Nfo

15/ 479
Add / 15479 31
31 / 479
 Virtual Memory Using Segmentation

- In segmented virtual memory system, a programmer views a program to be collection of


program component called segments.
- Each segment is logical unit of set of program.
- In programming terms, a segment usually consists of procedures or data that forms a
module of some s/w system.
- The work of segmentation is to group together procedures for implementing program in
large s/w system.
- Each logical address in segmented program is viewed to be a pair.
(si, wi)
where,
Si – Segment id.
Wi – Word, respectively

 Memory Compaction
- To eliminate external fragmentation, OS can periodically perform memory compaction.
- Produce a single unused area in memory.
- This memory / area may be large enough to accommodate one or more new program.
- Fig:

(A) (B) (C)

10 K Supervisor Supervisor Supervisor

30 K A A A

44 K B C C

16 K C D D

24 K D 46 K E
48 K
4K 2K

- Initially program A, B, C, D are in execution


o Compaction is done when program B terminates.
o This produces a single unused area of 48k bytes.
o Program E with size 46k bytes can now be initiated in this memory area.
o This leaves 2k bytes of single unused area.
- Compaction involves movement of program in memory during execution
- Dynamic relocation of program.

 Garbage Collection
- Garbage collection is selective reuse of memory fragements.
- When program terminates & release its allocation, OS searches through a list of program
waiting for memory allocation & select a program which is executed at that memory area.
- 2 criteria :
1) First fit criteria
2) Best fit criteria
- First fit criteria selects program which is executed in free area, i.e. first program with size
<= z (z = memory unit)
- Best fit find largest program with size < z this leads to smaller hole in allocation thus
reducing the amount of usable memory.
- Consider a system which has 170 Kbytes available for user program.
Let the following program await memory allocation.

Program name size


C 40K
D 90K
E 55K
F 70K

-The 1st fit policy would initiate program C and D leading to total fragmentation of 40K bytes.
-The best fit policy would initiate program D and F leading to total fragmnentation of 10 K bytes.

-Fig:
 Non Contiguous Memory Allocation
- To overcome the drawback of contiguous memory allocation (memory fragmentation) the
effective solution is Non Contiguous memory allocation.
Eg – checks how non contiguous allocation is use to avoid fragmentation.
- 4 unallocated memory area of 50, 30, 80 & 60k bytes exist in memory.
- Program p require a total of 140k bytes is loaded into three. P program part existing in these
different areas as P-1, P-2, P-3 respectively.
- Free memory area now exist in following parts P-3 & program D is memory. These area is
use to initiate another program of size <= 80k. This avoids external fragmentation.
- Since the program part P1, P2 & P3 in fig have the size of 50, 30 & 60 bytes, XYZ lies in
P2 & has memory address of say 212488.
- An instruction in P-1 uses the address 62 488 to access XYZ. This address should be
corrected to 212488. This is best done by h/w unit that is located on path of memory i.e. the
process of correcting an address is called address translation.
- The address of memory location where the operand is actually located is called as effective
memory address of operand.
- Figure shows program execution when non contiguous memory allocation model is used.
The arrow shows access of XYZ by instruction of program P.
- Dotted arrow shows how the access is actually implemented during an execution of P.
- ATU corrects the address of XUZ to point at actual memory where XYZ exist.
- ATU corrects each memory address generated by program in this manner.

Fig: (A) (B)

50 P-1
10 K
(A)
Supervisor
(B)
Supervisor
(C)
Supervisor
F F
30 k
30 K A A A

44 K B C C

16 K C D D
Block Other

24 K Ready

I/O Proc
CP
Running

U1
Terminate

Blocked
Memory

Main Mem. CPU 2

I/O Proc
ATU

15/ 479
MR NO Nfo

46 K E
I/O Units I/O Units

31
Add / 15479
31 / 479
48 K
4K 2K
D

P-2
k C XYZ
C
80 k
20 k P-3 Addr = 22,488
D
60 k D
Chapter : 4 STARTING WITH UNIX

 Unix Architecture (Introduction to Unix)


- Unix architecture is a operating system architecture developed in 1969 by a group of AT &
T employee at Bell labs.
- The term Unix is use to describe any OS that conforms to Unix standards, etc.
- Unix is widely used in both server & workstations.
- Unix was design to be portable, multitasking & multi-user in time sharing configuration.
- Unix are characterized by various concepts.
1) Use of plain text fro storing data.
2) A hierarchical file system.
3) Treating devices & certain types of IPC (inter process communication)
4) Use of large number of s/w tools.
- Under Unix, the OS consist of many of these utilities along with master control program
called kernel.
- Kernel provides service to start & stop programs, handles the file system & other common
low level task that more program shares.
- Unix OS is a set of program that acts as a link between computer & user.
- Computer that allocates the system resources & co-ordinates all the details of computers
internal is called OS or kernel.
- 4 basic concepts that unite all version of Unix are the following 4 basics.

1) Kernel
Kernel is a hear of OS
It interacts with h/w & most of task like memory management, file management
etc, i.e. interaction with end user application shells etc.
Unix derives most of its functionality via kernel.

2) Shells
Shell is utility that process your request.
When you type in a command at your terminal, the shell interprets the command
& calls the program that you want.
Shell use standard syntax for all commands.
C shell, Bourne shell & kornshell are most famous shells, which are available
with all Unix.

3) Commands & utilities


There are various commands & utilities, which you would use, in day-to-day
activities. CP, mv, cat & grep etc are example of commands & utilities.
Number of various commands which has optional options.

4) Files & directories


Data in Unix is organized into files.
All files are organized into directories.
These directories are organized into tree like structure called file system.

 Feature of Unix
- Some key features of Unix Architecture are as follows :
1) Unix system utilize a centralized OS kernel which manage system & process
activities
2) Unix system are multitasking
i.e. multiple process can run at the same time, or within a small time slice &
nearly at same time & that process is interrupted & moved out of execution by
kernel. This is known as thread management.
3) Files are arranged / stored on disk in hierarchical file system.
i.e. with a single top location throughout system (“root” or “/”) with both files &
directories, subdir, sub-subdir & so on, on below it.
Fig of Unix Architecture

Application
Program

ksh bash
sh
more
Text
Processor csh
ps
Mail
cpp which
H/W
cnv
comp

as cat
Kernal FTP
shell ed
DBMS vi

 Types of Shells
There are different shells available in Unix. Most popular are as follows :
1) Bourne shell
2) Korn shell
3) C shell
- Shell means any program that user can use to type command.
- When user logs in to system shell program is automatically executed.
- The program is called shell because it hides the details of OS behind shell interface & manages
the technical details.

1) Bourne shell :-
- Bourne shell is one of the most important shell used in early version of Unix OS & becomes
a standard.
- It is written by Stephen Bourne in Bell labs.
- Bourne shell program name is sh & it is typically located in Unix file system hierarchy at
/bin/sh.
Features :-
1) Scripts can be invoked as commands by using their filename.
2) Provide set of built in commands
3) Provide flow control constructs, quotation facilities & functions.
4) Provide local & global variable scope.
5) Support I/O redirection & pipelines.

2) Korn shells :-
Korn shell is a Unix shell which was developed by David Korn in AT & T Bell labs in
1980.
- It includes many features of c shell such as command history.
- Main advantage of ksh over Unix shell is it is use as programming language.
- The kshg3 version support Associative array & built in floating point arithmetic.
- It is interactive command language that provides access to Unix system & to many other
systems, on many different computers & workstation on which it is implemented.
- Korn shell language is also complete, powerful, high level programming language for
writing application. (more easy & quick than other HLL)
- Korn shell has its own features & better than Bourne & c shell.
- Ksh program are easier to write & more concise & readable that c language.
- Has much better scripting language than any other popular language.
- Code is large.
- Ksh provide better performance.
- Korn shell language use the same syntax for built in command as for non built in
commands.

3) C shell :-
- C shell (csh) is a Unix shell developed by (Bill Joy for Berkeley s/w
distribution [BSD])
- Scripting syntax is modeled after the c programming language.
- Main use of c shell is as an interactive shell, but one can write program using c shell.
- It has customizable environment.
- A short hand can be assigned to command or sequence of command which is frequently
used.
- By assign an alias with alias command, one can essentially create their own command, i.e. it
has abbreviate command.
- It has job control.
- Programs can be urn in background or foreground.
- One can write program-using shell.
- C shell has Programming feature such as
1) checking of file permission
2) variable assignment
3) built in variable

 Commands :-
1) Login commands
2) Logout
3) Password
4) Who
5) Who am I
6) Clear

1) Password:- Changing your password.


This command allows you (user) to change the password.
It expects user to respond 3 times
1) It prompts for old password.
2) It checks whether user has entered a valid password.
3) & if he has, it then prompt for new password.
Syntax : - password
Example :- $ Password
Enter login password : ******
New password : ****
Re-enter password : ****
Password successfully changed for user.

2) Logout : Signing Off


This command is used to suspend a session for time being.
Syntax : logout
Example ; $ logout
Login :

3) WHO : Who are the users?


OS maintains the account of all user who are logged on to the system.
Who command displays a list of information of users :
- 1st column shows username,
- 2nd column shows device name,
- 3rd & 4th column shows date & time of logging in
- last column shows the machine name from where user has logged in
Syntax : - who
Example : - $ who
Name Line Date Time Machine
Root Console Jan 7 7.55 1.92.168.0.7

4) Who am I :-
This command displays the information about the user who invoked the
command.
Syntax :- who am I
$ Who am I
Root Console Jan7 7.56 192.168.0.1

Options :-
1) - u :-
It add time slice last activity (also called as idle time) & PID of each
process logged in.
$ who – u
root console Feb 13 12.30 7354
2) – q :-
Quick option simply shows login id‟s & count the logged in users.
$ who – q
= users = 2

5) Clear :-
Clears the terminal.
This command clears the screen.
Syntax :- clear
Chapter : 5 UNIX FILE SYSTEM & RELATED COMMANDS

 Unix File System overview :-


- All utilities, application, data in Unix is stored as files.
- Even a directory is treated as file, which contains several other files.
- Unix file system has upside down tree (hierarchical)
- File system begins with directory called root & root directory is denoted by (l).
- Branches from root there are several other directions called as bin, lib, usr, etc. Amp & dev.
- Root directory also contains a file called Unix, which is Unix kernel itself.
- These directories are called subdirectories.
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 devices like terminal, printer, disk drives etc.
Usr - In usr directory there are several directories, each associated with a particular user.
- These directories are created by system Administrator when he creates account for different
users.
- Under usr directory there are another bin directory which contains additional Unix
command files.
Tmp – contains temporary files created by Unix or by user.
Directory Contains
Bin Binary Executable files
Lib Library Function
Dev Device related files
Etc Binary Exe. files req. for SA
Tmp Temporary files created by Unix/user
Usr Home directories of all users
/usr/bin Additional binary exe. files.
 Types of files
- File is nothing but a container for storing information/data.
- In Unix, directories & devices are also treated as files.
- A directory is simply a folder where you store filename & other directories.
- Physical devices like hard disk, memory CD-ROM, printer & modem are treated as files.

3 types of files

1) Ordinary files :-
- Also known as Regular file.
- Contains only data as stream of character.

2) Directory File :-
- Its commonly said that a directory contains files & other directories but it contains their
name & number associated with their name.

3) Device files :-
- Device & peripherals are represented by files.
- To read / write a device, you have to perform operation on its associated file.

 Ordinary (Regular) File :-


- Ordinary files are most common type of file.
- Program written by user is belong to this type i,e all data, source program,object and
executable code and file created by the user.
- Commands like cat,ls etc are treated as ordinary files.
- Ordinary file is divided into 2 types:
o Text file
o Binary file
- Text file contains only printable character & also we can view the content of the particular
file.
- Binary file contains both printable & unprintable character that covers the entire ASCII
range (0 to 255).
- Most Unix commands are binary files, object code & executables that is produce by
compiling c program are also binary files.
- Pictures, sound & video files are also binary files.

 Directory Files :-
- Directory file keeps 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 & numerical reference to the
location of item.
- The reference is called as i - number & index to the table is called i – list.
- i-list is a complete storage space available to file system.

 Device Files :-
- Device file represent I/O devices, tty (terminal), a disk drive or a printer because Unix treat
such device as files.
- A degree of compatibility can be achieved between I/O (device) & ordinary I/O , allowing
for more efficient use of s/w.
- Device files can be either
o Character special file
o Block special file.
- Character special file can be deals with stream of character.
- Block special file deals with operates on larger block of data.
- Typical block size are 812 bytes, 1024 & 2048 bytes.

 Links :-
- A link is ptr to another file.
(directory is list of name & i-number of file)
- There are 2 types of links,these are.
- Hard link  i-number pts directory to another file.
- Soft link  (symbolic link) provides an indirect ptr to file.
- Soft link is implemented as directory file entry containing a path name.

 Unix File & Directory Permission :-


The Unix file system allows you to control, read, write & execute access to your files an the
basis of user, group & other.

 File types & permission

On Unix file system, every file & directory is owned by specific user.
- Permission assign to user can apply to specific file.
- File effective permission that have applied to specific user in relation to a file are
determined in logical precedence.

 Basic Permission :-
There are 3 specific permission on Unix like system that apply to each class.
1) Read permission :-
Which grant the ability to read a file, when set for a directory, this permission grants the
ability to read the names of file in the directory.

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. This permission must be set for executable
binaries in order to allow the OS to run them.
When set for directory, this permission grants the ability to traverse its tree in order to
access files or subdir, but not see files inside the directory.
r - indicate read permission
w – indicates write permission
x – execute permission

 Directory Permission :-
Directories also have its own permission & the significance of these permission differ a
great deal from those of ordinary files.
If default directory permission are not altered, the theory still appears.
Eg :- $ ls – ld programs.
Drwxr – xr – x 2 kumar metal 320 May9 9.57pm
The default permission of directory are rwxr – xr –x

 R Options – Recursive Options :-


It is possible to apply the chmod command recursively to all files & subdirectories in
directory. This is done with R option & need only directory name as Argument.
Chmod – R a + x programs
This makes all files & subdirectories executable by all user.

 Related Commands
1) ls :-
ls command is use to list the name of any file contained in current directory as well as
content of any subdirectories.
Syntax :- ls [option] [filename]
Useful Options :-
(1) ls – a
This option includes file beginning with a period in the list.
(2) ls – R
This option produce a recursive listing all files & subdirectories under the
current directory.
- r  reverse
- s  order by size
- t  creation time
- u  sort by access time
(3) ls – l
This option of ls include additional information (mode, number of link, owner,
group, size in bytes & time of last modification) for each file in list.
2) Cat :-
This command is use to concatenate & displays a file, i.e. it has 3 related functions with
regard to text file.
1) displaying
2) combining
3) creating new one
Syntax :- cat [option] [filename] [-] [filename]
[ ] – terms are optional

1) The most common use of cat command to read the content of file.
Syntax :- cat file 1
cat file 1 > file 2
the content of file 1 is written in file 2.
2) Concatenation :-
Concatenation is the 2nd role of cat is concatenation.
Eg :- cat f1 f2 f3.
This command will concatenate copies of content of 3 files f1, f2, f3

The concatenated output is just redirected using the O/P redirection


operator to another file, such as f4
Eg :- cat f1 f2 f3 > f4

3) File creation :-
File creation is the 3rd use of cat is file creation for small files it is easier
than by using vi other editors.
Eg :- cat > file 1

This command is use to create new file i.e. file 1.


Therefore press enter & simultaneously pressing ctrl + d key
if file 1 already exist then it will be overwritten (i.e. all contents are
erased) by new file.
Note:Cat command can also be use to simultaneously create a new file & transfer to it the data
from existing file.
This is accomplish by typing cat, the name of file in which the output will come, the output
redirection operator & name of file to be created.
Then by pressing enter cause :-
1) new file to be created & written to
eg – cat file 1 > file 2
this command creates a new file named as file 2 that contains copy of content of
file 1.
(there is no effect on content of file 1)

3) cd :-
The cd (change directory) command change the current working directory to named
directory.
Syntax :- cd dirname
Options
1) cd temp dir
this is use to change directory to temp dir.

2) cd ..
move back one directory.

4) Rmdir :-
This command is use to remove /delete a directory from system.
Syntax :- rmdir directory name.
The directory must be empty while removing.

5) Mkdir
This command is use to create a directory.
Syntax :- mkdir directory name

6) Copying file (cp) :-


This command is use to copying a file.
Syntax :- cp file 1 web docs
Copy file into directory
- Cp file 1 file 1 back
Make back up of file 1
7) pwd :-
this command is use to find out what directory you are working in
syntax :- pwd
8) rm (remove file) :-
this command is use to remove file from your directory.
Syntax :- rm file name
Eg :- rm foo
remove foo? Y  use to remove single file
rm letter *  remove all files
remove letter 1? Y
remove letter 2? Y
remove letter 3? N
9) chmod
this command is use to change the permission of file / directory.
Eg :- chmod a + r essay – 001
This command make a file essay.001 readable by everyone.
Eg :- chmod + x my command
To make a file eg shell script my command executable.
To check the permission of file use ls – l
10) date :-
This command is use to check date & time.
Syntax :- date
Fri Jan6 08:52:42 1995
11) echo :-
this command echoes its argument.
Syntax :- eg – echo this
This

12) grep :-
this command is use to find which file contain certain word.
Syntax :- grep <str> <files>
Eg – dict file contains
One way
Two ways
grep one dict 
one way
13) head :-
this command is use to look the head of file
syntax :- head essay . 001
it displays the first 10 lines of files essay .001
To see a specific number of lines,
Eg – head – n 20 essay.001
This displays first 20 lines of file.
14) more :-
This command is use to read text files one page at a time.
Syntax :- more file name
Eg :- more poem
It let you read a file poem, one page at a time.
Options :-
q – quite more
spacebar – next page
return key – read next line
b – go back one page
15) tail :-
This command is use to look at the tail of file
Syntax :- tail f1
Eg – tail essay.001
Displays last 10 lines & for displaying last 20 lines
tail - n 20 essay.001
16) wc :-
This command is use to count number of characters, word & lines in files.
Suppose a file XYZ contains
One
Two
Three
Syntax :- wc XYZ
3 3 11
This shows XYZ file contains 3 lines, 3 words & 11 characters.
Options :
Wc – l XYZ (lines)
3
wc – w XYZ (words only)
3
wc – c XYZ (characters)
11
17) sort :-
This command is use to sort a file
Syntax :- sort file name
18) touch :-
This command let you change the date on file & also use to create a blank file.
Eg – touch f1
This will change the access date & time of f1 to current time
If f1 doesn‟t exist it will create a file (blank).

19) In :-
In creates link between files
- symbolic link are special files that contains the absolute or relative path to separate file.
- Reference to symbolic link are forwarded to file it points to
- The file to which the reference is forwarded is not aware of the link, if the file pointed to is
moved or deleted the link will just point to nothing.
- In Unix all information about file are stored in inode (file name). File name is stored in
directories where i-node number (OS refer to file) are paid with file name.
- The number of links entry in the inode keep tracks of how many times the inode number
has been paired with name in directory.
- Hard link –w when creating with In, the source file is only use to determine the inode
number.
- A new inode no-to-file name entry is then made in some directory using that inode number
& number of links counter is incremental.
- There is same file everyday i.e. file can be accessed by different names & / or different
location.
- Moving or deleting „original‟ source file has no effect on other links.
- Eg – to make soft link “hello”
“/home/alice/code/bin/world”
syntax:- In – s/home/alice/code/bin/world hello

20) Chown :-
Use to change owner & group of files. Normally root is allowed to do this but if user
owns a file, then that user can change the group, but only the groups containing that
user.
Options :-
-R
Recursively change / owner / group of entire directory tree.
-h
change owner of link, not target file
-f
indicates no error if change failed
eg – root changes the ownership of “/etc/password” & “/etc/shadow” to user root, group
wheel
 chown root : wheel/etc/password/etc/shadow.
The same but changing the owner
 chown root : /etc/{password, shadow}
The same but changing the group
 chown : wheel/etc/{password, shadow}

21) man :-
man command is use to display help on syntax of Unix command.
Syntax :- man [option] [file]
Eg – man who
Obtain the information of who command.
Man – k password

22) Umask (modify file permission during creation)


When files & directories are created the inherited permission are
rw – rw – rw (octal value 666) for regular files
rwxrwxrwx (777) for directories
The umask system call kills 2 birds with one stone, i.e. pt set the mask to value specified
as argument, but it also returns the previous value of the mask
mode _t umask (mode_t cmask) ;
syntax :- $ umask

To change umask, enter umask & three digit number that specifies your new umask
Eg – to change your umask to 027 enter following command.
$ umask 027
Unix determines the default modes by subtracting your umask from the octal number
777 i.e. if your umask is 027, your default directory mode is 750.
Chapter : 6 TEXT EDITING WITH Vi EDITOR

 Introduction to vi editor
The vi is most commonly used text editing tool in Unix
- 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 it is fast & powerful editor.
- vi has no menus, but instead you use combination of key strokes in order to accomplish
commands.
- Last line is used for special information.
- The lines are mark with (v) tilde.

 Modes in Vi
Each mode has its own characteristic / operation. There are 3 different modes
1) command mode
2) insert mode
3) last line mode (command line mode)

1) Command modes :-
After a file is opened it is opened in command mode, that is s/p from
keyboard will be treated as vi commands & you will not see the word
you are typing on screen.

2) Insert modes :-
To enter the text you have to print / put vi in insert by pressing “i” or “a”
after that you can type / add text on screen.
To switch between modes Esc key is used
Esc (i) – text mode
Esc (command mode)

3) Last line :-
Entered by :,/,? Or !
Input is read by echoed at the bottom of the screen.
- command executed by <RETURN> or <ESC> terminated by ^C

 Existing in Vi
1) Quit without saving :
If you don‟t want to save the work : q will take you out without saving your
editing in vi.

2) Write & quit :


: w – saves the current file but don‟t exit but you type : wq it save & exit.

3) Forced quit :
An ! sign at the end of exit command (:q!, :wq!) causes a forced quit form vi
after ignoring / writing all changes.

Vi COMMANDS

 Moving Cursor in file

Left h
Right i
Up k
Down j
Line
Beginning ^ or B
End $
Sentence
Next sentence )
Previous sentence (
Paragraph
Next }
Previous {
File
Go to end of file :$
One character forward :w
One word forward :W
Go to line number :line_number
Displaying file information ^g
Inserting & appending
Insert text to left of cursor i
Insert in beginning of line I
Append to right a
Append to end of line A
Adding a new line
Adding a new line below
current line o
Add above current line O
Deleting the text
Delete text above the text x
Delete text character on right of
cursor X
th
Delete 20 line 20d
Delete current line dd
Delete till end of current line D
Replacing a character & word
Replace character above cursor r
Replace character until
ESC is pressed R
Replace the word from cursor
to end indicated by $ sign cw
Replace till end of line c
Substitute
Substitute current character s
Substitute entire line S
Undo the last change
Undo last change u
Undo last to current line U
Copy & pasting lines
Copy the current line
into buffer YY
Copy 5 lines from
current line 5YY
Paste the current buff. P
Searching
Searches for word name
in file :/name
n continue search forward n
N search back word N
Saving
Save but don‟t quit :w
Save & quit the editor :wq
Save zz
Quit without saving q!
Search & replace s / <search – string> / <replace>
Repeating last command .
Recovering an unsaved vi file vi – r filename
Chapter : 7 I / O REDIRECTION & PIPING

 Concept of Redirection :-
Redirection is the switching of standard stream of data so that it come from a source other than
its default source or so that it goes to some source or so that it goes to some destination other than
default destination.
OR
In Unix, to send O/P from a process to different device or another process via a pipe or process
read its I/P from different file, device or pipe.

According to 1st Definition, in Unix OS each command & process, is automatically assigned 3
data streams
1) one I/P stream called as standard i/p
2) two data stream called as standard o/p & standard error.

All consist of plaint text (human readable alphanumeric character) & are considered as type of
text file, & all are associated with console (keyword & text mode display screen by default.
Console  instrument panel containing
Terminal  equipment including a display monitor & keyboard connected to computer
- Command specifies program to run
- Process is instance of program in execution.
- Standard input is the source of input for command (text type in keyboard by default) but it
can be redirected to come from some other source such as file or another program.
- Standard output & standard error are the destination of output & error messages from
command (display monitor by default) but they can be redirected to go to other destination
(file, printer or another program)
- By using the standard stream makes the redirection in simple manner & it is the major
factor in flexibility & convenient of Unix like OS.
because by using standard stream has advantage that process do not need to be aware
the redirection occurring & simplifies the program development.
- Redirection device can be classified into 2 categories :
1) argument
2) redirection operators
- argument is the name of file or other data that is provided to command in order for
command to use it as input & it redirects standard I/P from being the keyboard to being that
file or data.
Example:-
If the head command, (read the 1st 10 lines of text, it is used without any
argument
head
It will read the 1st 10 lines of text type 10 at keyboard i.e. standard I/P, & repeat those
lines to standard o/p (display)
- This can be seen by pressing Enter () which moves on next line for typing the desired text.

After entering some text, pressing  enter key again move to another new line allowing
command to be executed by simultaneously pressing ctrl + d key.

- This means the text was typed at keyboard to be read from standard I/P & then be written
to next line of display screen.
- When a file named,
Eg
File 1 is used as argument with head, standard I/P is redirected from being a
keyboard to being that file i.e.
Head file 1
- Standard I/P could just as easily redirected with multiple argument, so that I/P data comes
from multiple file.
Eg – head file 1 file 2 file 3
- In this case, the head will by default read the 1st 10 lines from each file & write them to
display screen.

 Redirection Operators

- Redirection operators can be used to switch both the source & destination of standard
stream of data in commands.
- They can be classified as
1) I/P
2) O/P
3) Error
4) Pipe
- Can be formed mainly from 3 characters
1) leftward pointing angle bracket (<)
2) rightward pointing angle bracket (>)
3) vertical bar (|)
- 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, can be used
(<).
Eg – the standard I/P for head can be redirected to file named file 4 with the following
head < file 4
& same by using argument i.e.
head file 4
- Standard o/p & standard error both are by default the display screen. (when a command is
issued in absence of any redirection the two o/p stream will be displayed on 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
file 5 from displayed screen to file name files 6, with following :

Cat file 5 > file 6


- The content of file 5 are written to file 6 & are not visible on display monitor
- No effect on content of file 5
- Standard error can be redirected by using the standard error redirection operator, which
consist of rightward facing angular bracket preceded directly by using numeral 2.
(technical reason for number 2 is that each of 3 data channel is controlled via file
descriptor)
- File descriptor is numerical identifier maintained by OS i.e.
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
: nofile : no such file or dir.
- Standard error can be easily redirected from monitor to file
head no file 2 > file 7
- An alternative is use the append operator which add the o/p to end of designated file rather
than overwriting it.
- Append operator is a rightward pointing angel bracket & standard error append operator is
designated by number 2 followed by 2 brackets.
- This is useful for log files
Eg – head no file 2 >> log file
This will append the error message to end of log file.
- Pipes differ from other redirection operators in this they redirect the standard o/p of one
command to become a standard I/P of another command
Eg – standard o/p of ls command becomes the I/P for wc i.e.
ls | wc
This ability to redirect o/p of other commands allows number of commands to be string together to
form a pipelines of commands that can perform highly specific task that would be very difficult or
tedious by any other means.

 Piping

 Standard input and standard output constitute two separate streamsthat can be individually
manipulated by shell.
 We kmow that who command is use to produce a list of users,one use per line. if you save this
output in file and apply the wc-l command to count the number of lines in this file, then you
would have effectively counted the number of users.
 This method have certain disadvantages:
 You require an intermediate file that has to be removed after the wc command
has completed its run.
 The process is slow
 Difficult to handle complex task.
 When handling large files,it can occupy space of the disk.
 The shell enables the standard output of one command to be connected as standard input to
another. A special operator is used to do this – the | (pipe),which acts as a connector of two
commands. A pipeline is use to count the number of differences between two files.
 In a pipeline, all programs run simultaneously.
 The feature of pipelining represent one of the most important aspect oif unix system.
 A common use for pipes is to control the output of large files to the screen.
 Unix allows you to connect processes by considering the standard o/p of one process feeds
into I/P of another process this mechanism is called as pipes
 Connecting simple processes in a pipeline allows you to perform complex taxk without writing
complex program.
o Eg – how could you use head & tail in pipeline to display lines 25 through 75 of file?
 cat file | head 75 | tail 50
 The cat command feeds the file into pipeline. Head command gets the 1st 75 lines of file &
passes them down the pipeline to tail.

 Combining I/O Redirection and Piping:

 Combining piping, i/o redirection, and program execution provides a general


technique for performing complex operation by putting together simple
commands.
 Since programming languages run under Unix,your home-grown program which
reads and write to your terminal can easily be converted to one reads and write
to files instead.
 Suppose you are fed up and wish to change myprog from prompting you for
input from your terminal to reading its input from a file infile. You do this with:

%myprog < infile Execute myprog,input file infile.


 If you want to examine the output from myprog in a civilized manner via more
you would combine these tricks,
%myprog < infile | more input from infile, output to more.
 If you still find you‟re wading through too much output, you can have Unix
search through your programs‟s output for, say ,the specific string uninitialized
with:
%myprog < input-file | grep uninitialized | more.
Chapter : 8 ADVANCE TOOLS IN UNIX

1) Finding patterns in files :-


a) grep
The grep command allows you to search for specified pattern in one or more
files, printing any lines which contains specified pattern.
Syntax :- grep <str> <file>

Useful options :-
1) grep – i pattern file
print all lines of file that contains the pattern, regardless of case.
Eg – grep – i cg data
Print any line of data that contations “cg” “Cg” “cG” or “CG”
The –i option ignores the case of string when searching
2) grep –v pattern file
prints all lines of file except those that contains patterns.

b) Fgrep
Fgrep searches file for one or more pattern argument
It does not use regular expressions instead it does direct string
comparision to find matching line of i/p
c) Egrep
Works in similar way, but use extended regular explanation
matching patterns
Eg – egrep p{2}*

2) Working with column & fields


1) cut:-
this command is use to cut out selected fields of each line of file

OR
Cut command selects the list of column or fields from one or more files.
Options –c is for column
-f is for field
it is entered as

cut option [files[


for eg – if the file named test file contains

this is first line


this is second line
this is third line
cut –c1, 4, test file then
ts
ts
ts
it is printing column 1 & 4 of this file which contains t & s
Options
-c list cut the column position identified in list
-f list will cut the field identified in list

2) paste
paste command merge the lines of one or more files into vertical column
separated by tabs
if for eg – the files contains
this is first line
& file 2 contains
this is file 2
then by executing / running this command

paste files file 2 > output file

this will put into output file


this is first line this is file 2
It contains content of both file in column
Who/paste
Will list user in 2 column

Options
-d „char‟ separates column with char instead of a tab
-s merge subsequent file lines form one file.

3) Join :-
Join command is use to join lines of 2 files in common field
Options : - - a print a line for each unpairable line in file.
-e replace empty o/p field

3) Tools for Sorting :-


1) Sort
This command is use to sort the line of file or files in Alphabetical order
Eg – the file 1 contains the following contents

Zzz
Aaa
1234
yuer
wer
qww
wwe
then after executing sort file 1
o/p
1234
aaa
qww
wer
wwe
yuer
zzz
Options :-
-b ignores leading space & tabs
-c checks whether file are already sorted
-d ignores punctuation
-i ignores non printing characters
-n sort in arithmetic order
-o file put o/p in file
+m[-m] skip n fields before sorting & sort up to field position m.
-r reverse the order of sort
-u identical line in o/p file appear only one time in o/p

2) Uniq :-
This command removes duplicate adjacent lines from sorted file while
sending one copy of each second file.
Syntax :- sortnames | uniq – d

This will show which line appear more than once in names file

Options :-
-c prints each lien once, counting instance of each
-d prints duplicate line once, but no unique lines
-u prints only unique lines

4) Comparing files :-
1) Cmp :-
This command compares 2 files
Eg- suppose there are two files
File one file two
Then cmp file one file two will give
File one file two differ : char 80, line 4
If this command run on one file nothing will return as o/p

2) Diff:-
Compare the 2 file & print out the difference between 2 files.
Eg – there are 2 files

File 1 File 2
sss sss
then then
123 123
two 456
3c3

O/p – 123
456
3) (cu) :-
this command is used for communication over a modem or direct line
with another Unix system.
Syntax :- cu option destination

Option :-
-bn process line using n bit char (7 to 8)
-d print diagnostics
-e sends even parity data to remote system
-n prompts the telephone number

Destination :-
Telno is telephone number of modem which we connect
to
System call the system known to UUCP
Aadr is an address specific to LAN

5) Changing information in files


1) Sed :-
This command launches a stream line editor which you can use at
command line
You can enter your sed commands in a file & then by using –f option
you can edit your file & it work as
Sed [option] files
Options :-
-e „instruction‟ apply the editing instruction to file
-f script – apply the set of instruction from editing script
-n suppress default o/p
Note – If you want more information about sed enter man sed at
command line in your system.

6) Tools for displaying Date & Time


1) Cal :-
Cal command will print the calendar on current month by default
If you want to print calendar of August 1965
Syntax : -cal 8 1965

The cal command can be used without argument, in this case it displays
the calendar of current month

$ cal

2) Date :-
Displaying the system date
The Unix system maintains an internal clock meant to run perfectly
When system is shut down, a battery backup keeps the clock ticking.
You can display the current date with date command which shows date
& time to the nearest second.
Syntax :- $ date
Wed Aug 31 16:22:40 IST 2005
This command can be used with suitable format specified as argument.
Each format is preceded by + symbol, followed by % operator & single
character described formed
For eg- you can print only the month using the format +%m
$ date +%m
08
OR month name
$ date +%m
aug
OR you can combine them in one command
$ date + “%h %m”
Aug 08

7) Changing information in file


1) tr :- (translating characters)
mostly the commands have been handling either lines / columns
the tr (translator) is one type of filter which manipulate individual
character in line, i.e. it translates character using one or two compact
expression
syntax :- tr options expr 1 expr 2 std I/P
tr takes I/P only from standard I/P it does not take file name as argument
By default it translate each character in expression 1 to its mapped counter part
in expression 2
The 1st character in 1st expression is replace with 1st character in 2nd expression
& similarly for other characters.
Eg – to replace | with ~ (tilde)
& the / with – simply specific 2 expression containing these character in proper
sequence.
$ tr „|/‟ „~-„ < emp lst | head – n 3
Note :- the length of 2 expression should be equal. If they are not the longer
expression will have unmapped character.
It is easy to define the 2 expression as two separate variable & then evaluate in
double quote
Exp 1 = „|/‟ ; exp 2 = „~ - „
tr “$expr1” “$expr2” < emp lst

Options :-
- d deleting characters
- s compressing multiple consecutive characters
- c complementing values of expression
8) Tools for mathematical calculation
1) bc :- (the calculator)
Unix provides 2 types of calculator
1) a graphical object (X clac cmd)
2) text base bc command
When you use bc command without argument the cursor keeps on
blinking & nothing seem to happen.

bc belongs to family of commands (called filters) that except I/P form


keyboard when used without an argument.

$ bc
12 +5
17
(ctrl – d)
bc shows the o/p of computation in next line
Start bc again & then make multiple calculation in same line, using (;) as
delimiters.

O/p is shown in different line


Eg – 12*12 ; 2^32 (^ indicates power of)
144
4294967296
bc performs only integer computation & truncate the decimal portion that
is sees.
Eg – 9/5
1 Decimal portion is truncated

 Monitoring I/P & O/P


1) Script (recording your session)
this command is use to record your login session in file
- this command is useful to store in file all keystrokes as well as o/p & error messages
- you can later view the file. If you are doing some important work & you wish to keep a log
of all activities, you should invoke this command immediately after you log in
eg - $ script
Script started, file is type script
$_

- the prompt returns & all your keystrokes (including the one used to backspace) that you
now entered here get recorded in file typescript
- after your recording is over, you can terminate the session by entering exit
$ exit (or use ctrl + d)
script done, file is typescript
$_ (back to login shell)

2) tee : (creating a tee)


it is not feature of shell i.e. it is external command
- it handles character by duplicating its I/P
- it saves one copy in file & writes the other to standard O/P
- it is used as standard I/P & o/p, tee can be placed anywhere in pipeline.
- It does not perform any filtering action on its I/p, it gives exactly what it takes
Eg – the following command sequence use tee to display the o/p of who & saves this o/p in
file as well.
$ who | tee user txt

 Communication :-
1) telnet (remote login)
The telnet command, belonging to DARPA command set, allows you to log on a
remote machine.
If you have account on a host in local network (or on internet) you can use telnet
with hostname or lPadd as argument
$ telnet 192.168.35.12
trying 192.168.35.12
connected to 192.168.35.12
escape character is „^]‟
sunos 5.8
login :-
Using telnet protocol one can communicate with another host
You can close a telnet session in 2 ways
1st you can use the shell‟s exit command, or you can escape to the telnet
prompt <ctrl - ]> close the session, & quit to exit to the local shell.

2) Wall Communicating with users


The wall command addresses all users simultaneously. Most Unix system don‟t
permit user to run this command & reserve it for use of administrative
Syntax : -
Wall
The machine will shut down today at 14.30 hrs. the backup will be at
13:30 hrs
[ctrl + d]
- all users currently logged in will receive the message on their terminal & routinely executed
by administrator especially before shut down of system.

3) Write : -
By using this command you have 2 way communication with any person who is
currently logged in
- one user write a message & then waits for reply from other
- communication continue till both user decide to terminate conversation
- write uses login name of remote machine as arguments & text message form standard I/p
- Syntax :- $ write abc [message]

4) Mail :-
Mail is one of the well known command in Unix. It response is system
dependent but generally is prompts for subject to be enter before the main
message
$ mail abc
- mail is post marked with name of sender, as well as date & time of sending it
- there are number of internal commands that you enter at the & prompt
- you can save, delete, reply to or simply ignores the mail that you have received
- if you don‟t remember the different command you have to simply enter a ? for help.
- Mail saves message in mailbox which is normally placed in directory / var / spool/ mail &
has some name as login name.
- Once mail respond with an &  you can see the next message
- Enter + at the prompt to see further mail & - to display immediate preceding
message

Internal commands used by mail are as follows

Commands Action
+ print next message
- print previous message
N print message numbered N
h print header of all message
dN delete N message
uN undelete N message
sflame save current message with header & post mark in
flame
wflame save without hearder
muser forward mail to user
vN replies to sender of message N & delete after reply
q Quit mail program
!cmd run Unix command

5) News :-
The news command is use to read the message which is send by system
administrator
Syntax - $ news
News is meant to display all files that have been created in / usr / new since lat
time the command is executed.
When there are number of unread messages, news, by default, display them in
sequence, the most recent item shown 1st.
Options :-
-n displays only the file name of those messages that have not been
displayed
-s list the number of news items that have still not been read.

6) Finger :-
Has communicating features when used without argument it simply
produce a list of all logged user.
Unlike who finger can also provide details of single user
Syntax :- $ finger

 Process Related Commands


1) Ps :-
This command is to display process attributes
This command read through the kernel‟s structures & process table to fetch the
characteristics of processes
Ps displays the processes owned by the user running the command. If you
execute command immediately after logging in
$ PS
PID TTY TIME CMD
291 console 0:00 bash
each line show the PID, terminal (tty) & with which the process is associated
(controlling terminal) the cumulative processor time (TIME) that has consumed
since process has been started & process name (CMD)

Options –
-f full listing
i.e. to get the detailed listing which also shows the parent
of every process use - f (full) option
-u - displaying processes of user i.e. to know the activities of any user
-a - displaying all user process i.e. to know the activities of all users but
doesn‟t display the system processes.

2) Nice :-
Ni process in unix system are executed with equal priority. This is not always
advantageous because if any job has highest priority cannot be executed earlier.
So Nice command is used with & operator to reduce the priority of job
More important job can then have greater access to system resources
To run the job with low priority, the command name should be prefixed with
nice
Nice wc –1 uxmanual
OR
Nice wc – 1 uxmanual &
Nice value are system dependent & typically range from 1 to 19.
Command execute with nice value that is generally in middle of range usually
10.
Higher nice value implies a lower priority
Nice reduces the priority of any process by ranging the nice value.
You can specify the nice value explicity with –n option
Nice –n 5 wc –1 uxmanual &

3) Kill :-
Kill command is use to terminate process & can use one or more PID as its
argument by default uses the SIGTERM (15) signal thus.
Syntax :- kill 105
Terminate the job havingPID 105
If you don‟t remember the PID use PS to know that & then use kill
If all these process have same parent you may simply kill the parent in order to
kill all its children.

4) At :-
Unix provide a efficient facilities to schedule a job to be run at specified time of
day rather than now
The at & batch command make such scheduling possible
At take time of jot as a argument of execution, I/P come from standard I/P
Syntax :- $ at 12:10
At > empawk2 .sh
Ctrl d
Command will be executed using /user/bin/bash
It also takes key words now, noon, midnight, today & tomorrow which is used in
this command
Eg – at 15
At 5pm
At noon
At 9 am tomorrow
At now + 1 year
The job can be listed with the at – l & removed with at – r.

5) Batch :-
The batch command also schedule job for later execution, but unlike at,
job for later execution, but unlike at, job are executed as soon as system load
permits.
The command doesn‟t take any argument but uses an internal algorithm
to determine execution time.
Response of batch is similar to at
Syntax - $ batch < empawk2. sh
Command will be executed using / usr / bin /bash
Any job scheduled with batch goes to a special at queue from where if
can be removed with at – r

6) Cron :-
Cron command is use to execute program at regular intervals, i.e. every
minute it wakes up & look in control file.
Cron uses an unusual matching system for matching field. It set of
number is to delimited by comma.

7) Crontax :-
You can create your own crontab files with vi in the format
It uses standard I/p & when used without argument the I/p has come
from keyboard.

$ crontax cron.txt
you use crontax command to place the file in the directory containing
crontax file for cron to read the file again.
Eg – if XYZ run this command, a file named XYZ will be created in
/var/spool/cron/crontab containing the contents of cron.txt.

A cron tab file with –r option is removed when the system clock is reset,
cron is aborted & restarted cron should never be kill, not even by system
administrator.
Like at & batch the use of cron is controlled by some sytem file which
can be edited by SA.

8) Sleep :-
You may need to introduce some delay in shell script to set the user see
some message on screen before the script start doing something else.
Sleep is the command which delay in shell script. Argument use with this
command is number of seconds for which the shell will pause or sleep
before it resumes execution.
Syntax :-
$ sleep 100 10 seconds have elapsed
The message appears exactly 10 second after the command have been
invoked.

9) Wait :-
The parent then executes the wait system call to wait for the child
process to complete.
It picks up the exit status of child & then continues with its other
functions.

 Concept of Mounting a file system.


The unix mount & unmount command are used for mounting & unmounting file systems.
To mount a file system to the root file system an empty directory must be made first & make
available in main file system.

1) Mount command :-
This command is important for handling file system, & has its own
configuration files which it reads when invoked.
Mounting is achieved with the mount command which normally takes 2
argument the system of file system & the directory under which it is to be
mounted.
Syntax :- $ mount / dev / abc

 Concept of Demounting a File System


Unmounting is achieved with unmount command, which today requires either the file system
name or the mount point as argument,
You can use either of the two commands to unmount the file system which user just mounted
$ unmount / abc
Chapter : 9 Shell Programming

 Shell keywords :-

Keywords are the word whose meaning has already been defined to the shell.
- The keyword cannot be used a variable name because if we do so, we are trying to assign a
new meaning to the keyword which is not allowed by the shell.

- Keyword is also called as Reserved words

- Following is the list of keywords available in Bourne shell.

echo if until trap


read else case wait
set Fi esac eval
unset while break exec
Read only Do continue ulimit
shift done exit umask
export for return

Shell Variable :-

Variable in unix are of 2 types :-

1) Unix defined variable or system variable

These are standard variable which are accessible shell provides value of these variables.

- These variables are used by system itself & control the environment.
- We can change the value of these variable as per our preference & customize the system
environment.

2) User defined variables.


These are defined by user & mostly used in shell programming.

 Unix defined / System Variable :-


- Unix OS has defined these variable for its own use.

- The $ prompt that we see is default value of unix defined variable PS1 stands for system
prompt 1.

- We can assign different value to PS1 if we want the prompt to be something other than the
$.
$ PS1 = “HI”
So now everytime the system prompt you it displays not the $ but HI.

Variable Meaning

PS2 The system prompt 2, default value is “>”

PATH Define the path which the shell must search in


order to execute any command / file.

HOME stores the default working directory of user.

LOG NAME stores the login name of user.

MAIL Defines the file where the mail of use is stored.

MAIL CHECK Define the duration after which the shell checks
weather the user has received any mail .
By default value is 600
IFS Define the internal field separates, which is space
a tab, or new line.

SHELL Define the name of you default working shell.

TERM Define the name of terminal on which you are


working.

Interactive shell script using Read & Echo

The read command enables parameter value to be entered interactively by the user while the
script is running.
It is usual to provide a priompt for the user as in the script losted below (called greeting).
Echo “whats your name?”
Read name Echo “Hello, $ Name”
This can give the following results.
% greetings - execute the script what‟s your name?
Output Jenny _ the shell waits for your I/P
Hello, Jenny _ O/P %
The read statement in the shell‟s internal tool for taking I/p from user is making script
interactive. It is used to shell with one or more variables.
Input supplied through the std I/p is read into these variables.
When you use statement like
Read name
the script pauses at that pt to take I/p from keyboard.
More than one parameter can be given to read command, usually separated by one or more spaces as in
the following script (called count).
Echo How for can you count?
Read first second third
Echo first & second third
This can run to give full %count.
How far can you count?
123 - uses I/P 123 –script O/p
 DECISION STASTEMENT
1) If then fp.
The if statement makes 2 way decision depending on fulfillment of certain condition, In
shell the statement use the following forms.

1. If command is successful
Then
Execute command
Else
Execute command
fi

2. if command is successful
then
execute command
fi

3. If command is successful
then
Execute commands
elif command is successful then
else
fi

- If also requires a then it evaluate the success or failure of command that is specified in its
“command Line”

- If command succeeds the sequence of command following it is executed


- If command fails then else statement is executed.
- Every if is closed with corresponding fi & you will encounter an error if one is not present.
In the next script, emp3.sh (fig14.4}, grep is 1st executed & a simple if- else construct tests the exit
status pf grep.
This time we‟ll search /etc/password for the existence of 2 users. One exist in the file & other
doesn‟t.
$emp.3sh ftp
ftp:*:325:15: FTP user:/user1 /home ftp:/bin/true.
pattern not found – job over

$emp3. sh mail
pattern not found.

#!/bin/sh
#emp3. sh:Using if & else.
#if grep “^$1”/etc /password 2>/dev/null
(search U name at beg of the line.)

then
Echo “pattern found –job over”
Else
Echo “pattern not found “

fi

Test: (when you use to evaluate expression, you need the test statement because the true or false
values returned by explanation can‟t directly handle by if test uses certain operator to evaluate the
condition its eight &returns either a true or false exit status which is then used by if for making
decision.
test work in 3 ways
1> compare 2 no
2> cmp 3 string
3> check a file attribute.
Numerical comparison operator used by test
Operator Meaning
-eg equal to
-ne Not equal to
-gt greater than
-ge greater than or equal to
-if less than
-ie less than or equal to

- Test command can be used in its simplest form to test if a string exist as following script
% cat test 1 %test
echo “Type something please” Type something please
read a Hello
if test $a Thank you
then echo “thank you” %test 1
else echo “thanks for nothing” Type something please
fi Thanks for nothing
%

 Case conditional
The case statement is second conditional offered by shell.
The statement matches an explanation for more than one alternative & uses a compact construct
to permit multi way branching
- Case also handles string tests but in a more efficient manner than if
The general syntax stmt is follows
Case expression in
Pattern 1) commands 1;;
Pattern 2) command;;
Pattern 3) commmand 3;;
esac
1 eg
#!/bin/sh
#menu .sh:uses case to offer 5 item menu
#
echo “menu in
1.list of files/n
2.process of uses/n
3.todays date
4. uses of system/n
5.quit to unix/n
Enter your option:/c”
read choice
case “$choice” in
1)is -/;
2)ps-f;
3)date;
4)who ;
5) exit;
*echo “invalid option”
esac
Case 1st matches expressions with pattern 1

If the match succeeds than if executes command 1 which may be one or more commands
-If the match fails then pattern 2 match & so forth
Each command list is terminated with pair of semicolon &the entire constuioct is close with
esac (reverse of case).
Eg. Consider a simple script /menu sh.
That uses case .The script accept the value from 1 to 5 & perform action depend on number 5 Menu
choice are displayed with multilane echo stmt.
- Case matches the value of $choice with the string 1,2,3,4,5, If user enter! 11s-1
command is executed from eg 11 option 5 quit the pgm. The last option (*) matches any option not
matches by previous option.

 Looping stmt:-
1) for loop:-
the shells for loop differ in structure from the ones used in other programming language.
These is no three part structure or used in c, awk, perl.
Unlike white & until, for loop doesn‟t test he condition but instead of it uses list
Syntax:-
For variable in list
Do
Commands
Done
- the loop body also uses the keyboards do &done but additional parameter are variable
& list.
- Each white space separated word in list &that list is assigned to variable & command
are executed until list is exhausted.

Eg:-
$ for file in chap20 chap 21 chap22 chap23 ; do
>cp$file ${fike}.bak
>echo $file copied to file bak.
>done.
Chap 20 copied to chap 20 bak.
Chap 21copied to chap 21 bak.
Chap 22 copied to chap 22 bak.
Chap 23 copied to chap 23 bak.
-The list here comprises a series of character string (chap20 onwards) representing filenames
separated by whitespace.
-Each item in the list is assigned to variabe file. File 1st get the value chap20 ,then chap21 &so
on
-Each file is copied with a bak extension & cp,pleth message displayed after every file is
copied.

 While looping

While statement should be quite familiar to most programmer.


If repeatedly perform set of inst” until the control command return a true exit status.

Syntax:- whuile condition is true.


Do
Commands
Done

-The command enclosed by do & done are executed repeatedly till condition remains true.
Eg:- the script emp5.sh accept a code &description in same line & then writes the line to new list. It
then prompts you for more entries .The loop
It cet is controlled by value of $answer.

Eg:-#!/bin/sh.
#emp5.dh. dhow use of white loop
#
answer =(#must set to y for entering
while {“$answer”= “y”} the control command
do
echo “enter the code &descript :”>dev /tty.
Read code description #read both together.
Echo “$code/$description” >>new list .
(Append a line to new list)
echo “enter any moer (Y/N)?c”>dev/ttty
read any more
case $any more in
Y*/y*)answer=y;:
N*/n*)answer =N;:
*)answer = y; (any other reply means y)
esac
done

$emp5 :sh
enter code &descriptn :03 analgesice .
enter any more (y/n)?
enter code and description:04 analgesics.
Enter any more (y/n) ? (enter)
Enter the code and description 5 otc drgs
Enter any more (y/N)?
5) until :while complement
The until statement complement the while in sence of loop body that is executed repeatedly till
condition remains false
The general syntax of until loop is
Until [-r abc 1st] #until the file abc 1st can be read.
Eg:
Flag =y
Until test $flag = N
Do
Echo do it again?
Read flag
Done

 Comparison & logical operator


The operator use awk are <.>,==,!=>=,etc string comparison uses = = &!=operator but c shell
is clearly superior to bourne shell because it support 2 more operator.
+ matches wild card explanation
!doesn‟t matches wild card explanation

you can use the & & &!! operator in same form way you used them with awk ,bsh &p

 Positional parameter:-

Some unix command like date produce single line O/p we also pass command o/p through file
like grep &head to produce a single line we have to use external command (cut) to extract a field from
date o/p.

Case date!cut –D” “fi”in this ois overcome , the shell has internal cmd to do this job (set) set
assigns its argument positional parameter $1,$2,&so on this feature is especially use full for picking up
individual field from o/p of pgm.

Let use set to convert its argument to positional parameter.


$ set 9876 2895 6213
$-
This assign 9876 to positional parameter to $1 2345 to $2 6213 to $3.
It also sets the other parameter $# &$ # yo can verify by echoing each parameter
$echo 1st is $1 !$2/$2 /$3is $3
$1is 9876 $2is 2345 ,$36213.
$echo “the $1argument are $”
the 3 argument are 9876 2345 6213 .
we will now use command substitute” in extract individual field from date o/p &without using cut.
$set date.
$echo$*
wed Jan 8 09:40:35:1st 2003
$echo „
The date today is $2 $3 ,$6”
The date today is Jan 8 2003.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy