OS UNIX&Linux Study Material E-Notes All-Units-1
OS UNIX&Linux Study Material E-Notes All-Units-1
&p1
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
(1)What is operating System? Explain the abstract view of the components of a computer
system.
An operating system (OS) is a collection of software that manages computer hardware
resources and provides various services for computer programs. It acts as an
intermediary between the user of a computer and the computer hardware.
Os is one kind of system software which is directly interact with hardware device and
end user application program
Figure 1-1. A computer system consists of hardware, system programs, and application
programs.
The placement of the operating system is shown in Fig. 1-1. At the bottom is the
hardware, which, consists of integrated circuit chips, wires, disks, a key board, a monitor
and similar physical devices.
On the top of the hardware is the software.(1.system software 2.application software )
Operating system runs on the hardware and it provides base for the rest of the
software.
Most computers have two modes of operation: kernel mode and user mode.
The operating system is the most fundamental piece of software and runs in kernel
mode.
In this mode it has complete access to all the hardware and can execute any instruction
that the machine is capable of executing
The rest of the software runs in user mode, in which only a subset of the machine
instructions is available. Here we find the command interpreter (shell), compilers,
editors, and other system programs.
Finally, above the system programs are the application programs. These programs are
purchased or written by the users to solve their particular problems, such as word
processing, spreadsheets, web browser or music play To hide complexity of hardware.
&p2
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
Function of operating system
Operating systems perform two basically unrelated functions: providing a clean abstract set
of resources instead of the messy hardware to application programmers and managing
these hardware resources.
(1) Give the view of OS as an extended machine (Operating System as an Extended Machine)
The architecture (instruction set, memory, I/O, and bus structure) of most computers at
the machine level language is primitive and awkward to program, especially for input /
output operations.
The major task is to convert human readable form in to machine level language vice
versa
Users do not want to be involved in programming of storage devices and such kind of converter.
Operating System provides a set of basic commands or instructions to perform various
operations such as read, write, modify, save or close.
Dealing with them is easier than directly dealing with hardware.
To deal with such complexity, system program is available known as system call the task
of system call is to accepts command from user’s application software and generate
interrupt for the os
Thus, Operating System hides the complexity of hardware and presents a beautiful
interface to the users.
System call
Figure 1-2. Operating Systems turn ugly hardware into beautiful abstractions.
Just as the operating system shields (protect from an unpleasant experience) the
&p3
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
programmer from the disk hardware and presents a simple file-oriented interface, it
also conceals a lot of unpleasant business concerning interrupts, timers, memory
management, and other low level features.
In each case, the abstraction offered by the operating system is simpler and easier to
use than that offered by the underlying hardware.
In this view, the function of the operating system is to present the user with the
equivalent of an extended machine or virtual machine that is easier to work with than
the underlying hardware.
The operating system provides a variety of services that programs can obtain using
special instructions called system calls.
&p5
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
It keeps the track of which parts of memory are in use and free memory.
It allocates the memory to programs when they need it.
It de-allocates the memory when programs finish execution.
&p6
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
(4)Types of os
All the operating system consist of similar component and perform similar functions but the
method and procedure for performing these function are different.
Operating system classified in to different categories based on their features
cpu
• advance inputs
Batch- • cpu+memory=100 memory
1
• advance inputs
Batch- • nic+memory=40
storage
&p7
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
Advantages:
Move much of the work of the operator to the computer.
Increase performance since it was possible for job to start as soon as the
previous job finished.
Disadvantages:
Large Turnaround time.
More difficult to debug program.
Due to lack of protection scheme one batch job can affect pending jobs.
&p8
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
Advantages :-
Easy to use
User friendly
Quick response time
Disadvantages:-
If any problem affects the OS, you may lose all the contents which have stored
already
Unwanted user can use your own system in case if proper security options are not available
Advantages
&p10
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
Process
(1) What is Process? Give the difference between Process and Program.
Process:
Process is a program under execution.
It is an instance of an executing program, including the current values of the pro-
gram counter, registers & variables.
Process is an abstraction of a running program.
Process is start when cpu allocate to program
There are many resources are required to create process such as memory , cpu ,i/o files
Once a program is in the process there are many operation done on it like delete , suspend
interrupt , create and dead lock.
Process Program
A process is program in execution. A program is set of instructions.
A process is an active/ dynamic entity. A program is a passive/ static entity.
A process has a limited life span. It is A program has a longer life span. It is
created when execution starts and stored on disk forever.
terminated as execution is finished.
A process contains various resources A program is stored on disk in some file.
like memory address, disk, printer It does not contain any other resource.
etc… as per requirements.
A process contains memory address A program requires memory space on
which is called address space. disk to store all instructions.
Various fields and information stored in PCB are given as below:
Process Id: Each process is given Id number at the time of creation.
Priority : it comes in number lesser number has high priority.
Process state: The state may be ready, running, and blocked.
Program counter: The counter indicates the address of the next instruction to
be executed for this process.
CPU registers: The registers vary in number and type, depending on the com-
puter architecture. They include accumulators, index registers, stack pointers,
and general-purpose registers, plus any condition-code information. Along with
the program counter, this state information must be saved when an interrupt
occurs, to allow the process to be continued correctly afterward.
CPU-scheduling(event) information: This information includes a process
priority, point- ers to scheduling queues, and any other scheduling parameters.
Memory-management information: This information may include such infor-
mation as the value of the base and limit registers, the page tables, or the seg-
ment tables, depending on the memory system used by the operating system.
Accounting information(resource held): This information includes the amount
of CPU and real time used, time limits, account numbers, job or process
numbers, and so on.
Status information(Pcb pointer): The information includes the list of I/O devices
allocated to this process, a list of open files, and so on.the pcb pointer point to
the next pcb in sequence
&p12
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
READY STATE:
In this state process are ready to get excute , reside in main memory and wait for
theprocessor
RUNNING STATE:
Process shceduler select the job basis on the algorithem and send it to the
processor there are different types of algorithem as per the os.
WAITING STATE:
During the execuation of process any input is require then it send to the waiting
state and then ready state.if timer interrupt arise then it directly send to ready
state.
TERMINATED(FINISH) STATE:
Process shceduler terminate the process. It may be many situation like finish the
process,delete etc.
&p13
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
&p14
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
As processes enter the system, they are put into a job queue (batch jobs), which
consists of all processes in the system.
The processes that are residing in main memory and are ready and waiting to
execute are kept on a list called the ready queue and wait there until it is selected
for execution or dispatched.
The process therefore may have to wait for the disk. The list of processes waiting for
a particular I/O device is called a device queue. Each device has its own device
queue.
Once the process is allocated the CPU and is executing, one of several events could
occur:
The process could issue an I/O request and then be placed in an I/O queue.
The process could create a new sub process and wait for the sub process's
termination.
The process could be removed forcibly from the CPU, as a result of an
interrupt, and be put back in the ready queue.
Scheduler
Schedulers are special system software which handles process scheduling in various
ways.
Their main task is to select the jobs to be submitted into the system and to decide
which process to run.
Schedulers are of three types:
1. Long Term Scheduler
2. Short Term Scheduler
3. Medium Term Scheduler
Long Term Scheduler
It is also called job scheduler.
Long term scheduler determines which programs are admitted to the system for
processing.
Job scheduler selects processes from the queue and loads them into memory for
execution.
Process loads into the memory for CPU scheduling. The primary objective of the job
scheduler is to provide a balanced mix of jobs, such as I/O bound and processor
bound.
It also controls the degree of multiprogramming.
&p15
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
If the degree of multiprogramming is stable, then the average rate of process
creation must be equal to the average departure rate of processes leaving the
system.
On some systems, the long term scheduler may not be available or minimal.
Time-sharing operating systems have no long term scheduler.
When process changes the state from new to ready, then there is use of long term
scheduler.
Short Term Scheduler
It is also called CPU scheduler.
Main objective is increasing system performance in accordance with the chosen set
of criteria.
It is the change of ready state to running state of the process.
CPU scheduler selects process among the processes that are ready to execute and
allocates CPU to one of them.
Short term scheduler also known as dispatcher, execute most frequently and makes
the fine grained decision of which process to execute next.
Short term scheduler is faster than long term scheduler.
Medium Term Scheduler
Medium term scheduling is part of the swapping.
It removes the processes from the memory.
It reduces the degree of multiprogramming.
Running process may become suspended if it makes an I/O request.
Suspended processes cannot make any progress towards completion.
In this condition, to remove the process from memory and make space for other
process, the suspended process is moved to the secondary storage.
This process is called swapping, and the process is said to be swapped out or rolled
out.
Swapping may be necessary to improve the process mix. e of handling the swapped
out-processes.
&p16
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
(5)What is scheduling algorithm, Types of algorithm? How it is handled a process?
Basis on the algorithm which process execute first and which process execute last there are
two types of algorithm.
&p18
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
1 - Process
&p19
Haresh Khachariya, CS&IT nt | Operating System (2020-21)
Process Scheduling
(11) Explain FCFS, Round Robin, Shortest Job First, Shortest Remaining Job First and Priority
Scheduling algorithms with illustration.
I FCFS (First Come First Serve):
Selection criteria :
The process that request first is served first. It means that processes are served in the
exact order of their arrival.
Decision Mode :
Non preemptive: Once a process is selected, it runs until it is blocked for an I/O or
some event, or it is terminated.
Implementation:
This strategy can be easily implemented by using FIFO queue, FIFO means First In First
Out. When CPU becomes free, a process from the first position in a queue is selected
to run.
Example :
Consider the following set of four processes. Their arrival time and time required to
complete the execution are given in following table. Consider all time values in
milliseconds.
P2 3 2
P3 5 4
Gantt Chart :
P0 P1 P2 P3
0 10 16 18 22
Initially only process P0 is present and it is allowed to run. But, when P0 completes,
all other processes are present. So, next process P1 from ready queue is selected and
Process Arrival CPU Burst Finish Time Turnaround Time Waiting Time
Time (T0) Time (∆T) (T1) (TAT=T1-T0) (WT=TAT-∆T)
P0 0 10 10 10 0
P1 1 6 16 15 9
P2 3 2 18 15 13
P3 5 4 22 17 13
Advantages:
Simple, fair, no starvation.
Easy to understand, easy to implement.
Disadvantages :
Not efficient. Average waiting time is too high.
Convoy effect is possible. All small I/O bound processes wait for one big CPU
bound process to acquire CPU.
CPU utilization may be less efficient especially when a CPU bound process is
running with many I/O bound processes.
P3 5 4
Gantt Chart :
P0 P2 P3 P1
0 10 12 16 22
Initially only process P0 is present and it is allowed to run. But, when P0 completes,
all other processes are present. So, process with shortest CPU burst P2 is selected and
allowed to run till it completes. Whenever more than one process is available, such
type of decision is taken. This procedure us repeated till all process complete their
execution.
Statistics :
Process Arrival Time CPU Burst Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (Wt=TAT-∆T)
P0 0 10 10 10 0
P1 1 6 22 21 15
P2 3 2 12 9 7
P3 5 4 16 11 7
P1 1 6
P2 3 2
P3 5 4
Gantt Chart :
P0 P1 P2 P1 P3 P0
0 1 3 5 9 13 22
Initially only process P0 is present and it is allowed to run. But, when P1 comes, it has shortest
remaining run time. So, P0 is preempted and P1 is allowed to run. Whenever new process
comes or current process blocks, such type of decision is taken. This procedure is repeated
till all processes complete their execution.
Statistics :
Process Arrival time Completion Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (WT=TAT-∆T)
P0 0 10 22 22 12
P1 1 6 9 8 2
P2 3 2 5 2 0
P3 5 4 13 8 4
Advantages :
Less waiting time.
Quite good response for short processes.
Disadvantages :
Again it is difficult to estimate remaining time necessary to complete execution.
Starvation is possible for long process. Long process may wait forever.
Context switch overhead is there.
IV Round Robin:
Selection Criteria:
Each selected process is assigned a time interval, called time quantum or time slice.
Process is allowed to run only for this time interval. Here, two things are possible:
First, Process is either blocked or terminated before the quantum has elapsed. In this
case the CPU switching is done and another process is scheduled to run. Second,
Process needs CPU burst longer than time quantum. In this case, process is running
at the end of the time quantum. Now, it will be preempted and moved to the end of
the queue. CPU will be allocated to another process. Here, length of time quantum is
critical to determine.
Decision Mode:
Preemptive:
Implementation :
This strategy can be implemented by using circular FIFO queue. If any process comes,
or process releases CPU, or process is preempted. It is moved to the end of the queue.
When CPU becomes free, a process from the first position in a queue is selected to
run.
Example :
Consider the following set of four processes. Their arrival time and time required to
complete the execution are given in the following table. All time values are in
milliseconds. Consider that time quantum is of 4 ms, and context switch overhead is
of 1 ms.
P0 0 10
P1 1 6
P2 3 2
P3 5 4
Gantt Chart :
P0 P1 P2 P0 P3 P1 P0
0 4 5 9 10 12 13 17 18 22 23 25 26 28
At 4ms, process P0 completes its time quantum. So it preempted and another process
P1 is allowed to run. At 12 ms, process P2 voluntarily releases CPU, and another
process is selected to run. 1 ms is wasted on each context switch as overhead. This
procedure is repeated till all process completes their execution.
Statistics:
Process Arrival time Completion Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (WT=TAT-∆T)
P0 0 10 28 28 18
P1 1 6 25 24 18
P2 3 2 12 9 7
P3 5 4 22 17 13
Advantages:
One of the oldest, simplest, fairest and most widely used algorithms.
Disadvantages:
Context switch overhead is there.
Determination of time quantum is too critical. If it is too short, it causes frequent context
switches and lowers CPU efficiency. If it is too long, it causes poor response for short
interactive process.
P3 5 4 0
Here, process priorities are in this order: P3 > P2 > P1 > P0.
Gantt Chart :
P0 P3 P2 P1
0 10 14 16 22
Initially only process P0 is present and it is allowed to run. But, when P0 completes, all other
processes are present. So, process with highest priority P3 is selected and allowed to run till
it completes. This procedure is repeated till all processes complete their execution.
Statistics :
Process Arrival time Completion Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (TAT-∆T)
P0 0 10 10 10 0
P1 1 6 22 21 15
P2 3 2 16 13 11
P3 5 4 14 9 5
Process Arrival Time (T0) Time required for completion ( ∆T) Priority
P0 0 10 5
P1 1 6 4
P2 3 2 2
P3 5 4 0
Gantt chart:
P0 P1 P2 P3 P1 P0
0 1 3 5 9 13 22
Initially only process P0 is present and it is allowed to run. But when P1 comes, it has higher
priority. So, P0 is preempted and P1 is allowed to run. This process is repeated till all processes
complete their execution.
Statistics:
Process Arrival time Completion Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (TAT-∆T)
P0 0 10 22 22 12
P1 1 6 13 12 6
P2 3 2 5 2 0
P3 5 4 9 4 0
Advantages:
Priority is considered. Critical processes can get even better response time.
Disadvantages:
Starvation is possible for low priority processes. It can be overcome by using
technique called ‘Aging’.
Aging: gradually increases the priority of processes that wait in the system for a
long time.
Context switch overhead is there.
(2) Five batch jobs A to E arrive at same time. They have estimated running times 10,6,2,4 and 8
minutes. Their priorities are 3,5,2,1 and 4 respectively with 5 being highest priority. For each
of the following algorithm determine mean process turnaround time. Ignore process swapping
overhead.
Round Robin, Priority Scheduling, FCFS, SJF.
C 2 2
D 4 1
E 8 4
A B C D E
0 10 16 18 22 30
Process Arrival time Completion Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (TAT-∆T)
A 0 10 10 10 0
B 0 6 16 16 10
C 0 2 18 18 16
D 0 4 22 22 18
E 0 8 30 30 22
C D B E A
0 2 6 12 20 30
Process Arrival Completion Finish Time Turnaround Time Waiting Time
time (T0) Time (∆T) (T1) (TAT=T1-T0) (TAT-∆T)
A 0 10 30 30 20
B 0 6 12 12 6
C 0 2 2 2 0
D 0 4 6 6 2
E 0 8 20 20 12
Priority:
B E A C D
0 6 14 24 26 30
A 0 10 24 24 14
B 0 6 6 6 0
C 0 2 26 26 24
D 0 4 30 30 26
E 0 8 14 14 6
Round Robin:
Time slice OR Quantum time= 2min.
A B C D E A B D E A B E A E A
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
Process Arrival time Completion Finish Time Turnaround Time Waiting Time
(T0) Time (∆T) (T1) (TAT=T1-T0) (TAT-∆T)
A 0 10 30 30 20
B 0 6 22 22 16
C 0 2 6 6 4
D 0 4 16 16 12
E 0 8 28 28 20
(3) Suppose that the following processes arrive for the execution at the times indicated. Each
process will run the listed amount of time. Assume preemptive scheduling.
Process Arrival Time (ms) Burst Time (ms)
P1 0.0 8
P2 0.4 4
P3 1.0 1
What is the turnaround time for these processes with Shortest Job First scheduling algorithm?
(4) Consider the following set of processes with length of CPU burst time given in milliseconds.
Process Burst Time Priority
P1 10 3
P2 1 1
P3 2 3
P4 1 4
P5 5 2
Assume arrival order is: P1, P2, P3, P4, P5 all at time 0 and a smaller priority number implies a
higher priority. Draw the Gantt charts illustrating the execution of these processes using
preemptive priority scheduling.
The disadvantage of sorting the incoming jobs into separate queues becomes
apparent when the queue for a large partition is empty but the queue for a small
partition is full, as is the case for partitions 1 and 3 in Fig. 5-1(a).
Here small jobs have to wait to get into memory, even though plenty of memory is
free. An alternative organization is to maintain a single queue as in Fig. 5-1(b).
Whenever a partition becomes free, the job closest to the front of the queue that
fits in it could be loaded into the empty partition and run.
Partition - 4 Partition - 4
Single
Partition - 3 Input Partition - 3
Multiple
Queue
Input
Queues
Partition - 2 Partition - 2
Partition - 1 Partition - 1
Operating Operating
System System
Figure 5-1. (a) Fixed memory partitions with separate input queues for each partition.
(b) Fixed memory partitions with a single input queue.
Whenever any process gets terminate, it releases the space occupied. If the
released free space is contiguous to another free partition, both the free partitions
are merged together in to single free partition.
Better utilization of memory than fixed sized size partition.
This method suffers from External fragmentation.
Figure 5-2. Memory allocation changes as processes come into memory and leave it.
The shaded regions are unused memory.
(2) Explain memory management with Linked list and Bit maps.
When memory is assigned dynamically, the operating system must manage it.
In general there are two ways to keep track of memory usage.
Memory Management with Bitmap.
Memory Management with Linked List.
Memory Management with Bitmap
With bitmap, memory is divided into allocation units.
Corresponding to each allocation unit there is a bit in a bitmap.
Bit is 0 if the unit is free.
Bit is 1 if unit is occupied.
The size of allocation unit is an important design issue, the smaller the size, the
larger the bitmap.
The main problem is that when it has been decided to bring a k unit process, the
memory manager must search the bitmap to find a run of k consecutive 0 bits in the
map.
Searching a bitmap for a run of a given length is a slow operation.
Figure 5-3 shows part of memory and the corresponding bitmap.
Memory Management with Linked List
Another way to keep track of memory is to maintain a linked list of allocated and
free memory segments, where segment either contains a process or is an empty
hole between two processes.
The memory of Fig. 5-3(a) is represented in Fig. 5-3(c) as a linked list of segments.
Each entry in the list specifies a hole (H) or process (P), the address at which it starts
the length and a pointer to the next entry.
Figure 5-3. (a) A part of memory with five processes and three holes. The tick marks
show the memory allocation units. The shaded regions (0 in the bitmap) are free. (b)
The corresponding bitmap. (c) The same information as a list.
The segment list is kept sorted by address. Sorting this way has the advantage that
when a process terminates or is swapped out, updating the list is straightforward.
A terminating process normally has two neighbors (except when it is at the very top
or bottom of memory).
These may be either processes or holes, leading to the four combinations of Fig. 5-4.
In Fig. 5-4(a) updating the list requires replacing a P by an H. In Fig. 5-4(b) and Fig. 5-
4(c) two entries are merged into one, and the list becomes one entry shorter.
In Fig. 5-4(d), three entries are merged and two items are removed from the list.
(3) Given memory partition of 100K, 500K, 200K, 300K, and 600K in order, how would
each of the First-fit, Next fit, Best-fit and Worst-fit algorithms place the processes of
212K, 417K, 112K and 426K in order? Which algorithm makes the most efficient
use of memory? Show the diagram of memory status in each case.
First Fit:
Search Starts from the starting location of the memory.
First available hole that is large enough to hold the process is selected for allocation.
The hole is then broken up into two pieces, one for process and another for unused
memory.
Search time is smaller here.
Memory loss is higher, as very large hole may be selected for small process.
Here process of size 426k will not get any partition for allocation.
Next Fit:
Best Fit
Entire memory is searched here.
The smallest hole, which is large enough to hold the process, is selected for
allocation.
Search time is high, as it searches entire memory.
Memory loss is less. More sensitive to external fragmentation, as it leaves tiny holes
into which no process can fit.
Worst Fit
Entire memory is searched here also. The largest hole, which is largest enough to
hold the process, is selected for allocation.
This algorithm can be used only with dynamic partitioning.
Here process of size 426k will not get any partition for allocation.
The basic idea behind virtual memory is that each program has its own address
space, which is broken up into pages.
Each page is a contiguous range of addresses.
These pages are mapped onto the physical memory but, to run the program, all
pages are not required to be present in the physical memory.
The operating system keeps those parts of the program currently in use in main
memory, and the rest on the disk.
Virtual memory works fine in a multiprogramming system, with bits and pieces of
many programs in memory at once.
While a program is waiting for part of itself to be brought in, it is waiting for I/O and
cannot run, so the CPU can be given to another process.
In a system using virtual memory, the physical memory is divided into page frames
and the virtual address space is divided in into equally-sized partitions called pages.
(5) What is paging? Explain the conversion of virtual address in paging with example.
Paging
The program generated address is called as Virtual Addresses and form the Virtual
Address Space.
Most virtual memory systems use a technique called paging.
Virtual address space is divided into fixed-size partitions called pages.
The corresponding units in the physical memory are called as page frames.
The pages and page frames are always of the same size.
Size of Virtual Address Space is greater than that of Main memory, so instead of
loading entire address space in to memory to run the process, MMU copies only
required pages into main memory.
In order to keep the track of pages and page frames, OS maintains a data structure
called page table.
The conversion of virtual address to physical address
When virtual memory is used, the virtual address is presented to an MMU (Memory
Management Unit) that maps the virtual addresses onto the physical memory
addresses.
A very simple example of how this mapping works is shown in Fig. 5-6.
In this example, we have a computer generated 16-bit addresses, from 0 up to 64K.
These are the virtual addresses.
Figure 5-5. The relation between virtual addresses and physical memory addresses is
given by the page table.
frame number found in the page table is copied to the higher order bit of the output
register along with the offset.
Together Page frame number and offset creates physical address.
Physical Address = Page frame Number + offset of virtual address.
Figure 5-6. The internal operation of the MMU with 16 4-KB pages.
This strategy is called demand paging because pages are loaded only on demand,
not in advance.
Working Set
The set of pages that a process is currently using is known as working set.
Thrashing
A program causing page faults every few instructions is said to be thrashing.
Pre-paging
Many paging systems try to keep track of each process‘working set and make sure
that it is in memory before letting the process run.
Loading pages before allowing processes to run is called pre-paging.
Figure 5-8. Operation of second chance. (a) Pages sorted in FIFO order. (b) Page list if a
page fault occurs at time 20 and A has its R bit set. The numbers above the pages are
their loading times.
Whenever page frame k is referenced, the hardware first sets all the bits of row k to
1, and then sets all the bits of column k to 0.
At any instant, the row whose binary value is lowest is the least recently used; the
row whose value is next lowest is next least recently used, and so forth.
The workings of this algorithm are given in Fig. 5-11 for four page frames and page
references in the order 0 1 2 3 2 1 0 3 2 3.
After page 0 is referenced, we have the situation of Fig. 5-11(a).
After page 1 is reference, we have the situation of Fig. 5-11(b), and so forth.
As shown in Fig. 5-11(j), if page fault occurs at that moment, the page from the page
frame 1 with lowest binary value will be replaced.
Figure 5-11. LRU using a matrix when pages are referenced in the order 0, 1, 2, 3, 2, 1,
0, 3, 2, 3.
When page fault occurs, the operating system inspects all the pages and divide
them into 4 categories based on current values of their R and M bits
Case 0 : not referenced, not modified
Case 1 : not referenced, modified
Case 2 : referenced, not modified
Case 3 : referenced, modified
The NRU (Not Recently Used) algorithm removes a page at random from the lowest
numbered nonempty class.
In given example,
Page-0 is of class-2 (referenced, not modified)
Page-1 is of class-1 (not referenced, modified)
Page-2 is of class-0 ( not referenced, not modified)
Page-3 is of class-3 (referenced, modified)
So lowest class page-2 needs to be replaced by NRU.
(9) Compare optimal, LRU and FIFO page replacement algorithms with illustration.
OR
For the Page Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1
Calculate the Page Faults applying (i) Optimal (ii) LRU and (iii) FIFO, Page
Replacement Algorithms for a Memory with three frames.
Optimal Page Replacement Algorithm
The moment a page fault occurs, some set of pages will be in the memory.
One of these pages will be referenced on the very next instruction (the page
containing that instruction).
Other pages may not be referenced until 10, 100, or perhaps 1000 instructions later.
Each page can be labeled with the number of instructions that will be executed
before that page is first referenced.
The optimal page algorithm simply says that the page with the highest label should
be removed.
If one page will not be used for 8 million instructions and another page will not be
used for 6 million instructions, removing the former pushes the page fault that will
fetch it back as far into the future as possible.
The only problem with this algorithm is that it is unrealizable.
At the time of the page fault, the operating system has no way of knowing when
each of the pages will be referenced next.
Page 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Requests
Frame 1 7 7 7 2 2 2 2 4 4 4 0 0 0 0 0 0 0 7 7 7
Frame 2 0 0 0 0 3 3 3 2 2 2 2 2 1 1 1 1 1 0 0
Frame 3 1 1 1 1 0 0 0 3 3 3 3 3 2 2 2 2 2 1
Page Faults F F F F F F F F F F F F F F F
(15)
(10) A computer has four page frames. The time of loading, time of last access and the
R and M bit for each page given below. Which page NRU, FIFO, LRU will replace.
Page Loaded Last Ref. R M
0 126 280 1 0
1 230 265 0 1
2 140 270 0 0
3 110 285 1 1
FIFO
Page which is arrived first needs to be removed first, so here Page – 3 having
minimum loading time so as per FIFO page-3 needs to replace.
LRU (Least Recently Used)
When page fault occurs, throw out the page that has been used for the longest
time.
Page page-1 is not used for the long time from all four, so LRU suggest replacing
page-1.
NRU (Not Recently Used)
NRU make approximation to replace based on R and M bits.
When a process is started up, both page bits for all pages are set to 0 by operating
system.
Periodically, the R bit is cleared, to distinguish pages that have not been referenced
recently from those that have been
When page fault occurs, the operating system inspects all the pages and divide
them into 4 categories based on current values of their R and M bits
Case 0 : not referenced, not modified
Case 1 : not referenced, modified
Case 2 : referenced, not modified
Case 3 : referenced, modified
The NRU (Not Recently Used) algorithm removed a page at random from the lowest
nonempty class.
In given example
Page-0 is of class-2 (referenced, not modified)
Page-1 is of class-1 (not referenced, modified)
Page-2 is of class-0 ( not referenced, not modified)
Page-3 is of class-3 (referenced, modified)
So lowest class page-2 needs to be replaced by NRU
(11) What is page fault handling? How OS handles page fault handling?
2. An assembly code routine is started to save the general registers and other volatile
information, to keep the operating system from destroying it.
3. The operating system discovers that a page fault has occurred, and tries to discover
which virtual page is needed. Often one of the hardware registers contains this
information. If not, the operating system must retrieve the program counter, fetch
the instruction, and parse it in software to figure out what it was doing when the
fault hit.
4. Once the virtual address that caused the fault is known, the system checks to see if
this address is valid and the protection consistent with the access. If not, the
process is sent a signal or killed. If the address is valid and no protection fault has
occurred, the system checks to see if a page frame is free. It no frames are free, the
page replacement algorithm is run to select a victim.
5. If the page frame selected is dirty, the page is scheduled for transfer to the disk,
and a context switch takes place, suspending the faulting process and letting
another one run until the disk transfer has completed. In any event, the frame is
marked as busy to prevent it from being used for another purpose.
6. As soon as the page frame is clean (either immediately or after it is written to disk),
the operating system looks up the disk address where the needed page is, and
schedules a disk operation to bring it in. While the page is being loaded, the
faulting process is still suspended and another user process is run, if one is
available.
7. When the disk interrupt indicates that the page has arrived, the page tables are
updated to reflect its position, and the frame is marked as being in normal state.
8. The faulting instruction is backed up to the state it had when it began and the
program counter is reset to point to that instruction.
9. The faulting process is scheduled, and the operating system returns to the
assembly language routine that called it.
10. This routine reloads the registers and other state information and returns to user
space to continue execution, as if no fault had occurred.
Symbol Parse
Table Tree Call
Source Stack
Text
Constants
Segment Segment Segment Segment Segment
0 1 2 3 4
Figure 5-14 (a). The MULTICS virtual memory. The descriptor segment points to the
Page tables.
Figure 5-14. The MULTICS virtual memory. (b) A segment descriptor. The numbers are
the field lengths.
(13) Discuss the issues associated with paging and solution of it.
In any paging system, two major issues must be faced:
1. The mapping from virtual address to physical address must be fast.
2. If the virtual address space is large, the page table will be large.
The mapping from virtual address to physical address must be fast.
In the absence of paging, to fetch an instruction requires only one memory
reference.
With paging, one more memory reference is required to access the page table.
Since execution speed is generally limited by the rate at which the CPU can get
instructions and data out of the memory, having to make two memory references
per instruction reduce performance by half.
Most programs access a small number of pages frequently.
The solution that has been devised is to equip computers with a small hardware
device for mapping virtual addresses to physical addresses without going through
the page table.
The device, called a TLB (Translation Lookaside Buffer) or sometimes an associative
memory, is illustrated in Fig. 5-15.
It is usually inside the MMU and consists of a small number of entries, eight in this
example, but rarely more than 256.
Each entry contains information about one page, including the virtual page
number, a bit that is set when the page is modified, the protection code
(read/write/execute permissions), and the physical page frame in which the page is
located.
These fields have a one-to-one correspondence with the fields in the page table,
except for the virtual page number, which is not needed in the page table. Another
bit indicates whether the entry is valid (i.e., in use) or not.
Let us now see how the TLB functions.
When a virtual address is presented to the MMU for translation, the hardware first
checks to see if its virtual page number is present in the TLB by comparing it to all
the entries simultaneously (i.e., in parallel).
Doing so requires special hardware, which all MMUs with TLBs have.
If a valid match is found and the access does not violate the protection bits, the
page frame is taken directly from the TLB, without going to the page table.
If the virtual page number is present in the TLB but the instruction is trying to write
on a read-only page, a protection fault is generated.
When the virtual page number is not in the TLB, the MMU detects the miss and
does an ordinary page table lookup.
It then evicts one of the entries from the TLB and replaces it with the page table
entry just looked up.
Thus if that page is used again soon, the second time it will result in a TLB hit rather
than a miss.
When an entry is purged from the TLB, the modified bit is copied back into the
page table entry in memory.
The other values are already there, except the reference bit. When the TLB is
loaded from the page table, all the fields are taken from memory.
If the virtual address space is large, the page table will be large.
There are two ways of dealing with very large virtual address spaces.
1. Multilevel Page Tables
The secret to the multilevel page table method is to avoid keeping all the page
tables in memory all the time.
In particular, those that are not needed should not be kept around.
In Fig. 5-17(b) we see how the two-level page table works.
On the left we see the top-level page table, with 1024 entries, corresponding to the
10-bit PT1 field.
When a virtual address is presented to the MMU, it first extracts the PT1 field and
uses this value as an index into the top-level page table.
Each of these 1024 entries in the top-level page table represents 4M because the
entire 4-gigabyte (i.e., 32-bit) virtual address space has been chopped into chunks
of 4096 bytes.
The entry located by indexing into the top-level page table yields the address or the
page frame number of a second-level page table.
Entry 0 of the top-level page table points to the page table for the program text,
entry 1 points to the page table for the data, and entry 1023 points to the page
table for the stack.
The other (shaded) entries are not used. The PT2 field is now used as an index into
the selected second-level page table to find the page frame number for the page
itself.
Figure 5-17. (a) A 32-bit address with two page table fields. (b) Two-level
page tables.
Figure 5-18. Comparison of a traditional page table with an inverted page table.
All the virtual pages currently in memory that have the same hash value are
chained together, as shown in Fig. 5-18.
If the hash table has as many slots as the machine has physical pages, the average
chain will be only one entry long, greatly speeding up the mapping.
Once the page frame number has been found, the new (virtual, physical) pair is
entered into the TLB.
Paging Segmentation
Paging was invented to get large address Segmentation was invented to allow programs
apace without having to buy more physical and data to be broken up into logically
memory. independent address space and to add sharing
and protection.
The programmer does not aware that paging The programmer is aware that segmentation is
is used. used.
Address space is one dimensional. Many independent address spaces are there.
Procedure and data cannot be distinguished Procedure and data be distinguished and
and protected separately. protected separately.
Change in data or procedure requires Change in data or procedure requires compiling
compiling entire program. only affected segment not entire program.
Sharing of different procedures not available. Sharing of different procedures available.
Multiuser capability
In a multi user system the same computer resources hard disk, memory etc are
accessible to the many users.
Users are given the different terminal to operate, a terminal in turn, is a keyboard
and a monitor. All the terminals are connected to the main computer whose
resources are available by all users.
So the user at any of the terminals cannot use only the computer but also any
devices that may be attached like a printer.
Multitasking capability
It means that it is capable of carrying out more than one job at the same time it
allow you to type in a program in its editor while simultaneously executes some
other command you might have given earlier.
Say for example you might have given earlier sort and copy a huge file this job will
perform in the background while in foreground you use editor.
This is managed by dividing the CPU time between all processes being carrying out.
Communication
UNIX has the excellent communication with the users. The communication may be
within the network of a single main computer or between two or more such
computer network.
The users can easily exchange mail, data, and programs through such networks.
Security
Unix Has the three provisions for protecting the data. The first is provided by
assigning the passwords and login names to the individual users and ensuring that
nobody has excess to your work.
All the five have the read write and execute permissions to each file which decide
who can excess a particular file, which can modify and execute it.
Lastly there is a file encryption utility which encodes your file into an unreadable
format so even if someone succeeds in opening it your secrets are safe.
Portability
Portability means software can works on different types of hardware in same way.
It is one of the main reasons for the popularity of the Unix. It can be ported to
almost any computer system with only the minimum adoptions.
Haresh Khachariya Dept:CS&IT| – Operating System (2020-21)
2 – Introduction to UNIX
A portability credit of the UNIX is because of the C language, it written in C
language and C language is portable.
User
Utility Program
Standard library
Hardware
Hardware
The bottom layer is hardware.
It contains physical devices of computer like CPU, Memory, Disk, printer etc.
UNIX kernel will interface with this hardware.
UNIX Kernel
Kernel is program which provides services of OS like memory management, file
management and process management.
Kernel will provide interface with hardware and user programs.
Standard library
It contains set of procedures.
This is collection of system level files.
Utility program:
Utility programs are used to make user programs and make work easier.
Utility programs like compilers, assemblers, editors etc.
User
User programs are comes for processing and interact with system.
At the lowest level it contains interrupt handlers which are the primary way for
interacting with the device, and low level dispatching mechanism.
The dispatching occurs when an interrupt happens and also when the kernel completes
some operations and it is time to start up a user process again.
Now we divide the various kernel subsystems into the three main components. The I/o
component contains the kernel pieces and responsible for interacting with the devices
and performing the network and storage I/O operations.
At the highest level the I/O operations are all integrated under a virtual file system and
at lowest level, all I/O operations pass through some device driver.
All Linux drivers are classified as either a character device driver or block device drivers,
with the main difference that random accesses are allowed on the block devices and
not on the character devices.
Technically network devices are really character devices, but they are handled
somewhat differently, so It is preferable to separate them.
The layer above the network drivers handle a kind of the routing function and making
sure that the right packet goes to the right devices.
Sockets interface which allows the program to create sockets for the particular
network.
On the top of the disk drivers is the I/O scheduler who is responsible for ordering and
issuing disk operation request in a way that tries to converse waste full disk head
movement.
At the very top of the block device column are the file systems Linux may have the
multiple file system excising concurrently. In order to hide the architectural differences
of the various hardware devices from the file system implementation, a generic block
device layer provides an abstraction layer used by all file system.
At the right side of the fig there are two key components of the Linux kernel these are
responsible for the memory and process management tasks.
Memory management tasks include maintaining the virtual to physical memory
mappings, maintaining a cache of the recently accessed pages and implementing a good
page replacement policy.
The key responsibility of the process management component is the creation and
termination of the process. It also includes the process scheduler and code for the
signal handling.
Finally at the very top is the system call interface in to the kernel. All system calls come
here, causing a trap which switches the execution from the user mode in to the kernel.
Mode.
(5) Explain the directory Structure or file system structure of the Unix/linux.
The initial Linux file system was the MINIX 1 file system. However, infect it limited file
names to 14 characters and its maximum file size was 64 MB.
The first improvement was the ext files system which allow file names of 255 characters
and file size of 2 GB, but it was slower than MINIX 1 file system so the ext 2 file system
was invented, with long file name, long file, and better performance and it has became
/:
This is the root directory which should contain only the directories needed at the top level of the
file structure.
/bin:
This is where the executable files are located. They are available to all user.
/dev:
Haresh Khachariya Dept:CS&IT| – Operating System (2020-21)
2 – Introduction to UNIX
It includes files for devices, holds the software necessary to update peripherals such as printers
and terminal.
/etc:
It contains various administrative files such as lists of user name and passwords, configuration
files, disk configuration files.
/mnt
Used to mount other temporary file systems, such as cdrom and floppy for the CD-ROM drive and
floppy diskette drive, respectively
/home
Contains the home directory for users and other accounts.
/tmp
Holds temporary files used between system boots
/usr
Used for miscellaneous purposes, or can be used by many users. Includes administrative
commands, shared files, library files, and others
/var
Typically contains variable-length files such as log and print files and any other type of file that
may contain a variable amount of data
Shell - As interface
Shell is interface between user and computer.
User can directly interact with shell.
Shell provide command prompt to user to execute commands.
Shell - As command interpreter
It read command enter by user on prompt.
It Interpret the command, so kernel can understand it easily.
Shell - As programming language
Shell is also work as programming language.
It provides all features of programming language like variables, control structures
and loop structures.
Korn shell : -
The Korn shell uses two startup files, the .profile and the .kshrc. The .profile is read once, by your
login ksh, while the .kshrc is read by each new ksh.
The Korn shell was developed in the early 1980s by David Korn of AT&T labs, and contains many
similar features to the sh and csh shells.
The Korn shell has an advantage over the traditional Unix shell in that it contains the
functionality of many scripting and programming languages, such as perl and awk, meaning that
programs can be run quickly and efficiently within the Korn shell.
Default prompt is $ denoted as ksh.
Bourne shell : -
It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is faster and
more preferred. It lacks features for interactive use like the ability to recall previous commands.
It also lacks built-in arithmetic and logical expression handling. It is default shell for Solaris OS.
Default prompt is $ for user denoted as sh.
Bourne-again shell : -
The Bourne-Again Shell (bash) is a clone of the Bourne shell, written and licensed under the GNU
General Public License, meaning the code for the shell, as well as the shell itself, is freely
available.
The bash shell runs using very similar syntax to the sh, ksh and csh shells. However, there are
some small changes with the bash shell. For example, the bash shell runs under all GNU/Linux
variant operating systems, such as Ubuntu and Debian.
The bash shell also supports many interactive features, such as a command history that can be
accessed with a few keystrokes.
It is the default shell on Linux operating system.
Default prompt is $ for user denoted as bash.
Symbolic Mode
In the Absolute mode, you change permissions for all 3 owners. In the symbolic mode, you can modify
permissions of a specific owner. It makes use of mathematical symbols to modify the file permissions.
Operator Description
Absolute(Numeric) Mode
In this mode, file permissions are not represented as characters but a three-digit octal number.
The table below gives numbers for all for permissions types.
0 No Permission ---
1 Execute --x
2 Write -w-
4 Read r--
In the above-given terminal window, we have changed the permissions of the file 'sample to '764'.
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29
Used to go back one directory on the majority of all UNIX shells. It is important
that the space be between the cd and directory name or ..
Example:-
$ pwd
/home/kumar
$ cd progs
$ pwd
/home/kumar/progs
$ cd ..
/home/kumar
file size.
Field 6 – Last modified date & time: Sixth field specifies the date and time of the
last modification of the file. In this example, ‘Jan 16 15:27′ specifies the last
modification time of the file.
Field 7 – File or directory name: The last field is the name of the file or directory.
In this example, the file name is file1.txt
6) exit :- It is used to terminate a program, shell or log you out of a network normally.
Syntax :- exit
8) who :- who command can list the names of users currently logged in, their terminal, the
time they have been logged in, and the name of the host from which they have logged in.
Syntax :- who [options] [file]
Description:-
Print the username of the invoking user, The 'am' and 'i' must be space
am i
separated.
-b Prints time of last system boot.
-d print dead processes.
-H Print column headings above the output.
Include idle time as HOURS:MINUTES. An idle time of . indicates activity
-l
within the last minute.
-m Same as who am i.
-q Prints only the usernames and the user count/total no of users logged in.
Example :-
$ who
dietstaffpts/1 2016-02-20 22:42 (:0.0)
dietstaffpts/2 2016-02-20 09:30 (:0.0)
Here first column shows user name, second shows name of the terminal the user
is working on. Third& fourth column shows date and time of logging, last column
shows machine name.
Description: - Print the user name associated with the current effective user id.
Example :-
$ who am i
dietstaffpts/3 2016-02-10 08:52 (:0.0)
Here first column shows user name, second shows name of the terminal the user
is working on. Third & fourth column shows date and time of logging, last column
shows machine name.
-p Allow users to remove the directory and its parent directories which become
empty.
12) bc:- bc command is used for command line calculator. It is similar to basic calculator. By
using which we can do basic mathematical calculations.
Syntax :- bc [options]
Description :-
bc is a language that supports arbitrary precision numbers with interactive
execution of statements.
bc starts by processing code from all the files listed on the command line in the
order listed. After all files have been processed, bc reads from the standard input.
All code is executed as it is read.
Example:-
$ bc
bc 1.06 Copyright 1991-1994,1997,1998,2000 Free Software Foundation,Inc. This
is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 2*3
6
The above command used is for mathematical calculations.
$ bc -l
bc 1.06 Copyright 1991-1994,1997,1998,2000 Free Software Foundation,Inc. This
is free software with ABSOLUTELY NO WARRANTY.For details type `warranty'.11+2
13
The above command displays the sum of '11+2'.
$ bc calc.txt
bc 1.06 Copyright 1991-1994,1997,1998,2000 Free Software Foundation,Inc. This
is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 13
'calc.txt' file have the following code:11+2. Get the input from file and displays the
output.
14) tty:- Print the file name of the terminal connected to standard input.
Syntax :- tty
Description :-
tty writes the name of the terminal that is connected to standard input onto
standard output.
Command is very simple and needs no arguments.
Example :-
$tty
/student/tty10
Example :-
$ sty
speed 19200 baud, 25 rows, 79 columns
kill = ^U
After inserting content you can use ctrl+d to exit the file.
If file with same name exist then it will overwrite that file.
$ cat file1.c
process management
memory management
file mgmt
$ cat file1.c >> file2.c
It can concatenate the contents of two files. For this you have to use append
output redirection operator.
The contents of file2.cwill be appended to file1.c.
17) cp:- cp command copy files from one location to another. If the destination is an existing
file, then the file is overwritten; if the destination is an existing directory, the file is copied
into the directory (the directory is not overwritten).
Syntax :- cp [options]... source destination
Description:-
Here, after cp command contents of both source file and destination file files are
the same.
It will copy the content of source file to destination file.
If the destination file doesn’t exist, it will be created.
If it exists then it will be overwritten without any warning.
If there is only one file to be copied then destination can be the ordinary file or the
directory file.
-a archive files
-f force copy by removing the destination file if needed
-i interactive - ask before overwrite
-l link files instead of copy
-L follow symbolic links
-n no file overwrite
-u update - copy when source is newer than dest
Example:-
$ cp file1 file2
The above cp command copies the content of file1.php to file2.php.
Copy folder and subfolders:
$ cp-R scripts scripts1
The above cp command copy the folder and subfolders from scripts to scripts1
20) nl :-
nl numbers the lines in a file.
Syntax: - nl [OPTION] [FILE]
Example :-
$cat list.txt
apples
oranges
potatoes
lemons
garlic
$nl list.txt
1 apples
2 oranges
3 potatoes
4 lemons
5 garlic
In the above example, we use the cat command to display the contents of list.txt.
Then we use nl to number each line and display the result to standard output.
$nl list.txt > nlist.txt
$cat nlist.txt
1 apples
2 oranges
3 potatoes
4 lemons
5 garlic
In the above example, we run the same nl command, but redirect the output to a
new file, nlist.txt. Then we use cat to display the results.
21) cut :- cut command is used to cut out selected fields of each line of a file. The cut
command uses delimiters to determine where to split fields.
Syntax :- cut [options] filename
Description :-
file A path name of an input file. If no file operands are specified, or if a file
operand is -, the standard input will be used
-c The list following -c specifies character positions
-d The character following -d is the field delimiter
-f select only these fields on each line
-b Select only the bytes from each line as specified in LIST
Example :-
For example, let's say you have a file named data.txt which contains the following
text:
one two three four five
alpha beta gamma delta epsilon
In this example, each of these words is separated by a tab character, not spaces.
The tab character is the default delimiter of cut, so it will by default consider a
field to be anything delimited by a tab.
To "cut" only the third field of each line, use the command:
$ cut -d’ ‘ -f 3 data.txt
three
gamma
let's say you want the third field and every field after it, omitting the first two
fields. In this case, you could use the command:
$ cut -d’ ‘ -f 3- data.txt
three four five
gamma delta epsilon
$ cut -c 3 file.txt
r
m
For example, to output only the third-through-twelfth character of every line of
data.txt, use the command:
$ cut -c 3-12 data.txt
e two thre
pha beta g
22) paste:- paste command is used to paste the content from one file to another file. It is also
used to set column format for each line.
Syntax :- paste [option] file
Description :-
Paste prints lines consisting of sequentially corresponding lines of each specified
file. In the output the original lines are separated by TABs. The output line is
terminated with a newline.
big file with thousands of records and we want to read that file then we should
use more command. Consider a file named employees then we will use following
command to read its contents a page at a time.
24) cmp:- It compares two files and tells you which line numbers are different.
Syntax : - cmp [options..] file1 file2
Description :-
Let’s create a file named os2. And use cmp command to compare os and os1files.
- c Output differing bytes as characters.
Print the byte number (decimal) and the differing byte values (octal) for each
-l
difference.
- s Prints nothing for differing files, return exit status only.
- c Output differing bytes as characters.
Example:-
$ cat file1
memory
process
files
$ cat > file2
memory
process
files mgmt
$ cmp file1 file2
File1 file2 differ: char 21, line 3
The two files are compared byte by byte and the location of the first mismatch is
echoed to the screen. cmp doesn’t bother about possible subsequent mismatches.
For example let’s create two files named file1 and file2 with following data.
$ cat > file1
c.k.shukla
chanchalsanghvi
s.n.dasgupta
sumit [1] + Stopped
single column output using 3 options -1,-2 or -3. To drop a particular column,
simply use its column number as a prefix.
Example :-
$ cat file1
f1.c
f2.c
f3.c
f4.c
f5.c
$ cat file2
f1.c
f3.c
f4.c
f6.c
f7.c
Now, When you run the comm command on these files, this is what you get:
$ comm file1 file2
f1.c
f2.c
f3.c
f4.c
f5.c
f6.c
f7.c
The output is split in 3 columns. Column1 indicates files which are unique in file1,
column 2 indicates files unique to file2. Column 3 indicates files common between
them. comm command provides some real good options with which you can filter
the output better.
Now, say you want to find out only the list of files which were there in the older
version but not in the newer version:
$ comm -23 file1 file2
f2.c
f5.c
The option -23 indicates to remove the second and third columns from the comm
command output, and hence we are left with only the first column which is the
files unique in file1.
Similarly, to find out the list of files which were not there in the old version, but
has been added in the new version:
ggg
hhh
$ diff 1.txt 2.txt
1d0
< aaa
3c2
< ccc
---
>cc
7a7
> hhh
Lines like "1d0" and "3c2" are the coordinates and types of the differences
between the two compared files, while lines like "< aaa" and "> hhh" are the
differences themselves.
diff change notation includes 2 numbers and a character between them.
Characters tell you what kind of change was discovered:
d – a line was deleted
c – a line was changed
a – a line was added
Number to the left of the character gives you the line number in the original (first)
file, and the number to the right of the character tells you the line number in the
second file used in comparison.
So, looking at the two text files and the diff output above, you can see what
happened:
1d0
< aaa
This means that 1 line was deleted. < aaa suggests that the aaa line is present only
in the original file.
3c2
< ccc
---
>cc
And this means that the line number 3 has changed. You can see how this
confirms that in the first file the line was "ccc", and in the second it now is "c c".
7a7
> hhh
Finally, this confirms that one new line appeared in the second file, it's "hhh" in
the line number 7.
27) chmod:- chmod command allows you to alter / Change access rights to files and
directories.
Syntax:- chmod [options] [MODE] FileName
Description :-
chmod command is used to set the permissions of one or more files for all three
categories of users (user,group and others ). It can be run only by the user and
super user. Command can be used in two ways. Let’s first take a look at the
abbreviations used by chmod command.
Category Operation Permission
u User + Assigns permission r Read permission
File Permission :
# File Permission
0 none
1 execute only
2 write only
3 write and execute
4 read only
5 read and execute
6 read and write
7 set all permissions
Relative permissions
When changing permissions in a relative manner, chmod only changes the
permissions specified in the command line and leaves the other permissions
unchanged. In this mode it uses the following syntax:
let’s first check the permission of file shortlist. It shows read/write permission.
Let’s assign execute permission to this file for owner.
$ ls –l
-rw-r--r—1 shortlist None 241 Feb 21 04:02
$ chmod u+x shortlist
$ ls -l
-rwxr--r-- 1 shortlist None 241 Feb 21 04:02
Here chmod uses expression u+x means – u shows user category that is user, +
shows we need to assign the permission and x shows execute permission.
Sameway we can assign other permissions.
Absolute permissions
Sometimes you don’t need to know what a file’s current permissions are, but want
to set all nine permission bits explicitly. The expression used by chmod here is a
string of three octal numbers. Each type of permission is assigned a number as
shown:
Read permission-4
Write permission-2
Execute permission -1
For each category we add numbers that represent the assigned permission. For
instance , 6 represents read and write permission , and 7 represents all
permissions.
Example :
$ chmod 666 myfile or(chmod u=rw,g=rw,o=rwmyfile) shortlist
Shows read and wrie (4 +2) permissions for all three types of users.
28) chown:- Command for system V that changes the owner of a file.
Syntax :- chown [options] newowner filename/directoryname
Description:-
Change the permission on files that are in the subdirectories of the directory that
-R
you are currently in.
-c Change the permission for each file.
Prevents chown from displaying error messages when it is unable to change the
-f
ownership of a file.
Example :-
$ ls -l demo.txt
-rw-r--r-- 1 root root 0 Jan 31 05:48 demo.txt
$ chownvivek demo.txt
-rw-r--r-- 1 vivek root 0 Jan 31 05:48 demo.txt
29) chgrp:- chgrp command is used to change the group of the file or directory. This is an
admin command. Root user only can change the group of the file or directory.
Syntax:- chgrp [options] newgroup filename/directoryname
Description:-
Change the permission on files that are in the subdirectories of the directory
-R
that you are currently in.
-c Change the permission for each file.
-f Force. Do not report errors.
Example :-
$ ls -l demo.txt
-rw-r--r-- 1 root root 0 Jan 31 05:48 demo.txt
30) file:- file command tells you if the object you are looking at is a file or a directory.
Syntax:- file [options] directoryname/filename
Description:-
File command is used to determine the type of file, especially of an ordinary file.
We can use it with one or more filenames as arguments. For example we can use
file command to check the type of the os1 file that we have created.
$ file os1
os1: short english text
31) finger:- finger command displays the user's login name, real name, terminal name and
write status (as a ''*'' after the terminal name if write permission is denied), idle time,
login time, office location and office phone number.
Syntax:- finger [username]
Description :-
-l Force long output format
-s Force short output format
Example :-
$ finger rahul
Login: abc Name: (null)
Directory: /home/abc Shell: /bin/bash
On since Mon Nov 1 18:45 (IST) on :0 (messages off)
On since Mon Nov 1 18:46 (IST) on pts/0 from :0.0
New mail received Thu Feb 7 10:33 2015 (IST)
Unread since Mon Feb 8 12:59 2016 (IST)
No Plan.
$ sleep 2m
To sleep for 3 hours, use:
$ sleep 3h
To sleep for 5 days, use:
$ sleep 5d
35) ps:- It is used to report the process status. ps is the short name for Process Status.
Syntax:- ps [options]
Description :-
-a List information about all processes most frequently requested: all those except
process group leaders and processes not associated with a terminal
-A List information for all processes. Identical to -e, below
-f Generate a full listing
-j Print session ID and process group ID
-l Generate a long listing
Example :-
$ps
36) ln :- ln command is used to create link to a file (or) directory. It helps to provide soft link
for desired files.
Syntax:- ln [options] existingfile(or directory)name newfile(or directory)name
Description:-
What Is A Link?
A link is an entry in your file system which connects a filename to the actual bytes
of data on the disk. More than one filename can "link" to the same data. Here's an
example. Let's create a file named file1.txt:
$ echo "This is a file." > file1.txt
This command echoes the string "This is a file". Normally this would simply echo to
our terminal, but the > operator redirects the string's text to a file, in this case
file1.txt
When this file was created, the operating system wrote the bytes to a location on
the disk and also linked that data to a filename, file1.txt so that we can refer to the
file in commands and arguments.
If you rename the file, the contents of the file are not altered; only the
information that points to it.
The filename and the file's data are two separate entities.
File1.txt
“This is a file””
What the link command does is allow us to manually create a link to file data that
already exists.
So, let's use link to create our own link to the file data we just created. In essence,
we'll create another file name for the data that already exists.
$ link file1.txt file2.txt
The important thing to realize is that we did not make a copy of this data. Both
filenames point to the same bytes of data on the disk. Here's an illustration to help
you visualize it:
File1.txt File2.txt
“This is a file”
If we change the contents of the data pointed to by either one of these files, the
other file's contents are changed as well. Let's append a line to one of them using
the >>operator:
$ echo "It points to data on the disk." >> file1.txt
Now let's look at the contents of file1.txt:
$ cat file1.txt
This is a file.
now let's look at the second file, the one we created with the link command.
$ cat file2.txt
This is a file.
ln, by default, creates a hard link just like link does. So this ln command:
$ ln file1.txt file2.txt
It is the same as the following link command. Because, both commands create a
hard link named file2.txt which links to the data offile1.txt.
$ link file1.txt file2.txt
However, we can also use ln to create symbolic links with the -s option. So the
command:
$ ln -s file1.txt file2.txt
It will create a symbolic link to file1.txt named file2.txt. In contrast to our hard link
example, here's an illustration to help you visualize our symbolic link:
File1.txt File2.txt
“This is a file””
You should also be aware that, unlike hard links, removing the file (or directory)
that a symlink(symbolic linkl) points to will break the link. So if we create file1.txt:
$ echo "This is a file." > file1.txt
Now, create a symbolic link to it:
$ ln -s file1.txt file2.txt
we can cat either one of these to see the contents:
$ cat file1.txt
This is a file.
$ cat file2.txt
This is a file.
But, if we remove file1.txt:
$ rm file1.txt
we can no longer access the data it contained with our symlink:
$ cat file2.txt
cat: file2.txt: No such file or directory
-s Makes it so that it creates a symbolic link
-f If the destination file or files already exist, overwrite them.
37) head:- head command is used to display the first ten lines of a file, and also specifies how
many lines to display.
Syntax:- head [options] filename
Description:-
Head command displays the top of the file. When used without an option , it
displays the first ten lines of the file.
-n To specify how many lines you want to display.
The number option-argument must be a decimal integer whose
-n number
sign affects the location in the file, measured in lines.
The number option-argument must be a decimal integer whose
-c number
sign affects the location in the file, measured in bytes.
Example :-
$ head myfile.txt
Display the first ten lines of myfile.txt.
$ head -15 myfile.txt
Display the first fifteen lines of myfile.txt.
$ head -c 20 myfile.txt
Will output only the first twenty bytes (characters) of myfile.txt. Newlines count as
a single character, so if head prints out a newline, it will count it as a byte.
$ head -n 5K myfile.txt
Displays the first 5,000 lines of myfile.txt.
38) tail:- tail command is used to display the last or bottom part of the file. By default it
displays last 10 lines of a file.
Syntax :- tail [options] filename
Description:-
Example:-
$ cat > data.txt
apples
oranges
pears
kiwis
bananas
$ sort data.txt
apples
bananas
kiwis
oranges
pears
Note that this command does not actually change the input file, data.txt. If you
want to write the output to a new file, output.txt, redirect the output like this:
40) find:- Finds one or more files assuming that you know their approximate path.
Syntax :- find [options] path
Description :-
Find is one of the powerful utility of Unix (or Linux) used for searching the files in a
directory hierarchy
path A path name of a starting point in the directory hierarchy
-maxdepth Descend at most levels (a non-negative integer) levels of directories
below the command line arguments.
-i ignore the case in the current directory and sub-directories.
give string:
$ echo "linux dedicated server" | tr "[:lower:]" "[:upper:]"
LINUX DEDICATED SERVER
$ echo "linux dedicated server" | tr "[a-z]" "[A-Z]"
LINUX DEDICATED SERVER
The -c option is used to replace the non-matching characters with another set of
characters.
$ echo "unix" | tr -c "u" "a"
uaaa
You can squeeze more than one occurrence of continuous characters with single
occurrence. The following example squeezes two or more successive blank spaces
into a single space.
$ echo "linux server" | tr -s " "
linux server
The following example removes the word linux from the string.
$ echo "linuxserver" | tr -d "linux"
Server
43) history:- history command is used to list out the recently executed commands in the
number line order.
Syntax:- history [options]
Description:-
The history command performs one of several operations related to recently-
executed commands recorded in a history list. Each of these recorded commands
is referred to as an ``event''.
$ history -a history.txt
This command is used to copy history list to history.txt file .
To Clear all history:
$ history -c
This command can be used to clear all history from history list.
45) grep:- It selects and prints the lines from a file which matches a given string or pattern.
Syntax:- grep [options] pattern [file]
Description:-
This command searches the specified input fully for a match with the supplied
pattern and displays it.
While forming the patterns to be searched we can use shell match characters, or
regular expressions.
Let us begin with the simplest example of usage of grep.
47) wc:- Word Count (wc) command counts and displays the number of lines, words,
character and number of bytes enclosed in a file.
Syntax: - wc [options] [filename]
Description:-
This command counts lines, words and characters depending on the options used.
It takes one or more filenames as its arguments and displays four-columnar
output. For example let’s read our os1 file. And we use wc command with that
filename.
-l print the newline counts.
-w print the word counts.
Example :-
$cat myfile.txt
Red Hat
CentOS
Fedora
Debian
Scientific Linux
OpenSuse
Ubuntu
Xubuntu
Linux Mint
Pearl Linux
Slackware
Mandriva
The ‘wc‘ command without passing any parameter will display a basic result of
”myfile.txt‘ file. The three numbers shown below are 12 (number of lines), 16
(number of words) and 112 (number of bytes) of the file.
$wc myfile.txt
12 16 112 myfile.txt
To count number of newlines in a file use the option ‘-l‘, which prints the number
of lines from a given file. Say, the following command will display the count of
newlines in a file. In the output the first filed assigned as count and second field is
the name of file.
$wc -l myfile.txt
12 myfile.txt
Using ‘-w‘ argument with ‘wc‘ command prints the number of words in a file. Type
the following command to count the words in a file.
$wc -w myfile.txt
16 myfile.txt
When using options ‘-c‘ and ‘-m‘ with ‘wc‘ command will print the total number of
bytes and characters respectively in a file.
$wc -c myfile.txt
112 myfile.txt
The ‘wc‘command allow an argument ‘-L‘, it can be used to print out the length of
longest (number of characters) line in a file. So, we have the longest character line
(‘Scientific Linux‘) in a file.
$wc -L myfile.txt
16 myfile.txt
48) man:- man command which is short for manual, provides in depth information about the
requested command (or) allows users to search for commands related to a particular
keyword.
Syntax:- man commandname [options]
Description :-
-a Print a one-line help message and exit.
-k Searches for keywords in all of the manuals available.
Example:-
$ man mkdir
Display the information about mkdir command
49) | (Pipeline command):- Used to combine more than one command. Takes output of 1st
command as input of 2nd command.
Syntax:- commmand1| command2|……
Example:-
$ls -l | grep "Feb"
-rw-r--r-- 1 dietstaffdietstaff 336 Feb 19 14:41 calc1.sh
-rw-r--r—1 dietstaffdietstaff 410 Feb 19 14:28 calc.sh
drwxr-xr-x 7 dietstaffdietstaff 4096 Feb 24 09:04 Desktop
drwxr-xr-x 7 dietstaffdietstaff 12288Feb 26 07:44 Downloads
drwxr-xr-x 3 dietstaffdietstaff 4096 Feb 26 08:55 lab
drwxr-xr-x 2 dietstaffdietstaff 4096 Feb 24 08:00 shellscript
-rw-r--r—1 dietstaffdietstaff 81 Feb 24 12:34 temp3.sh
%A Full weekday(Tuesday).
%b Abbreviated month name(Jan).
%B Full month name(January).
%c Country-specific date and time format..
%D Date in the format %m/%d/%y.
%j Julian day of year (001-366).
%p String to indicate a.m. or p.m.
%T Time in the format %H:%M:%S.
%t Tab space.
%V Week number in year (01-52); start week on Monday.
Example:-
$ date
Fri Feb 19 09:55:15 IST 2016
$ date +%m
02
$ date +%h
Feb
$ date +%y
16
$ date +"Date is %D %t Time is %T"
date is 19/02/16 Time is 10:52:34
To know the week number of the year,
$ date -V
11
To set the date,
$ date -s "10/08/2016 11:37:23"
The above command will print Wed Oct 08 11:37:23 IST 2016
2) wall :- send a message to everybody's terminal.
Syntax :- wall [ message ]
Wall sends a message to everybody logged in with their mesg(1) permission set to
yes. The message can be given as an argument to wall, or it can be sent to wall's
standard input. When using the standard input from a terminal, the message
should be terminated with the EOF key (usually Control-D).
The length of the message is limited to 20 lines.
Example : -
$sudo wall message.txt
Using the sudo command to run wall as the superuser, sends the contents
ofmessage.txt to all users.
1) Write a shell script to scans the name of the command and executes it.
Program :-
echo "enter command name"
read cmd
$cmd
Output :-
enter command name
cal
February 2016
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29
2) Write a shell script Which works like calculator and performs below operations Addition
, Subtract ,Division ,Multiplication
Program :-
i) using if..elif statement
echo " Enter one no."
read n1
echo "Enter second no."
read n2
echo "1.Addition"
echo "2.Subtraction"
echo "3.Multiplication"
echo "4.Division"
echo "Enter your choice"
read ch
if [ $ch = "1" ]
then
sum=`expr $n1 + $n2`
echo "Sum ="$sum
elif [ $ch = "2" ]
then
sum=`expr $n1 - $n2`
echo "Sub = "$sum
elif [ $ch = "3" ]
then
Output :-
Enter one no.
32
Enter second no.
12
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice
2
Sub = 20
Output :-
Enter one no.
32
Enter second no.
22
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice
2
Sub = 10
Do u want to continue ? y/n
N
3) Write a shell script to print the pyramid structure for the given number.
Program :-
echo "enter the number"
read n
printf "\n"
for((i=1;i<=$n;i++))
do
for((j=1;j<=$i;j++))
do
printf "$j"
done
printf "\n"
done
Output :-
enter the number
4
1
12
123
1234
4) Write a shell script to find the largest among the 3 given numbers.
Program :-
clear
echo "Enter first number: "
read a
echo "Enter second number: "
read b
echo "Enter third number: "
read c
if [ $a -ge $b -a $a -ge $c ]
then
echo "$a is largest integer"
elif [ $b -ge $a -a $b -ge $c ]
then
echo "$b is largest integer"
elif [ $c -ge $a -a $c -ge $b ]
then
echo "$c is largest integer"
fi
Output :-
Enter first number:
22
Enter second number:
33
Enter third number:
42
44 is largest integer
fact=1
echo "Enter number to find factorial : "
read n
a=$n
#if enter value less than 0
if [ $n -le 0 ]
then
echo "invalid number"
exit
fi
#factorial logic
while [ $n -ge 1 ]
do
fact=`expr $fact \* $n`
n=`expr $n - 1`
done
echo "Factorial for $a is $fact"
Output :-
Enter number to find factorial :
5
Factorial for 5 is 120
i=`expr $i + 1`
done
if [ $flag -eq 0 ]
then
echo $m
fi
m=`expr $m + 1`
done
Output :-
enter the range
10
the prime no are
2
3
5
7
Output :-
bash pr81.sh 123
Reverse of digits is 321 of 123
Output :-
How many numbers of terms to be generated?
5
Fibonacci Series up to 5 terms :
0
1
1
2
3
9) Write a shell script to check whether the given number is Perfect or not.
Program :-
echo Enter a number
read no
i=1
ans=0
while [ $i -le `expr $no / 2` ]
do
if [ `expr $no % $i` -eq 0 ]
then
ans=`expr $ans + $i`
fi
i=`expr $i + 1`
done
if [ $no -eq $ans ]
then
echo $no is perfect
else
echo $no is NOT perfect
fi
Output :-
Enter a number
6
6 is perfect
Enter a number
10
10 is NOT perfect
10) Write a shell script which displays a list of all files in the current directory to which you
have read, write and execute permissions
Program :-
for File in *
do
if [ -r $File -a -w $File -a -x $File ]
then
echo $File
fi
done
Output :-
Desktop
Documents
Downloads
lab
Music
Pictures
Public
shellscript
Templates
Videos
11) Write a shell script that deletes all the files in the current directory which are 0 bytes in
length.
Program :-
clear
find . -name "*" -size -1k –delete
echo “files deleted”
Output :-
files deleted
12) Write a shell script to check whether the given string is Palindrome or not.
Program :-
clear
echo "Enter the string:"
read str
echo
len=`echo $str | wc -c`
len=`expr $len - 1`
i=1
j=`expr $len / 2`
while test $i -le $j
do
k=`echo $str | cut -c $i`
l=`echo $str | cut -c $len`
if test $k != $l
then
echo "String is not palindrome"
exit
fi
i=`expr $i + 1`
len=`expr $len - 1`
done
echo "String is palindrome"
Output :-
Enter the string:
abba
String is palindrome
13) Write a shell script to display the digits which are in odd position in a given 5 digit
number
Program :-
echo "Enter a 5 digit number"
read num
n=1
while [ $n -le 5 ]
do
a=`echo $num | cut -c $n`
echo $a
n=`expr $n + 2`
done
Output :-
Enter a 5 digit number
12345
1
3
5
14) Write a shell script to check given year is leap year or not.
Program :-
clear
echo "enter any year"
read num
if [ `expr $num % 4` -eq 0 ]
then
if [ `expr $num % 100` -eq 0 -a `expr $num % 400` -ne 0 ]
then
echo "Not a leap year"
else
echo "Leap year "
fi
else
echo "Not a leap year"
fi
Output :-
enter any year
2016
Leap year
15) Write a shell script to find the value of one number raised to the power of another.
Program :-
echo "Input number"
read no
echo "Input power"
read power
counter=0
ans=1
while [ $power -ne $counter ]
do
ans=`echo $ans \* $no | bc`
counter=`echo $counter + 1 | bc`
done
echo "$no power of $power is $ans"
Output :-
Input number
5
Input power
3
5 power of 3 is 125
16) Write a shell script to display the following details in a pay list Pay slip details, House
rent allowance, Dearness allowance, Provident fund. HRA is to be calculated at the rate
of 20% of basic, DA at the rate of 40% of basic and PF at the rate of 10% of basic.
Program :-
i="y"
while [ $i = "y" ]
do
echo "Please enter your Basic:"
read basic
echo "PAY SLIP DETAILS"
echo "1. HOUSE RENT ALLOWANCE"
echo "2. DEARNESS ALLOWANCE"
echo "3. PROVIDENT FUND"
echo "your choice:"
read ch
case $ch in
1) hra=`expr $basic \* 20 / 100`
echo Your HOUSE RENT ALLOWANCE is Rs. $hra;;
2) da=`expr $basic \* 40 / 100`
echo Your DEARNESS ALLOWANCE is Rs. $da;;
3) pf=`expr $basic \* 10 / 100`
echo Your PPOVIDENT FUND is Rs. $pf;;
*) echo "Not a valid choice";;
esac
echo "Do u want to continue ?"
read i
if [ $i != "y" ]
then
exit
fi
done
Output :-
Please enter your Basic:
1000
PAY SLIP DETAILS
1. HOUSE RENT ALLOWANCE
2. DEARNESS ALLOWANCE
3. PROVIDENT FUND
your choice:
1
Your HOUSE RENT ALLOWANCE is Rs. 200
Do u want to continue ?
18) Write a shell script that greets the user by saying Good Morning, Good Afternoon, and
Good Evening according to the system time.
Program :-
clear
#hours=`date|cut -c 12-13`
hours=`date +%H`
if [ $hours -le 12 ]
then
echo "Good Morning"
elif [ $hours -le 16 ]
then
echo "Good Afternoon"
elif [ $hours -le 20 ]
then
echo "Good Evening"
else
echo "Good Night"
fi
Output :-
Good Afternoon
19) Write a shell script to generate mark sheet of a student. Take 3 subjects, calculate and
display total marks, percentage and Class obtained by the student.
Program :-
Clear
echo "Enter the five subject marks for the student"
read s1 s2 s3
sum1=`expr $s1 + $s2 + $s3`
echo "Sum of 5 subjects are: " $sum1
per=`expr $sum1 / 3`
echo " Percentage: " $per
if [ $per -ge 60 ]
then
echo "You get Distinction"
elif [ $per -ge 50 ]
then
echo “You get First class―
elif [ $per -ge 40 ]
then
echo "You get Second class"
else
echo "You get Fail"
fi
Output :-
Enter the five subject marks for the student
78 88 92
Sum of 5 subjects are: 258
Percentage: 86
You get Distinction
20) Write a shell script that finds total no. of users and finds out how many of them are
currently logged in.
Program :-
cat /etc/passwd>user.txt
set `wc -l user.txt`
log=`who|wc -l`
echo "There are $1 users in network "
echo "There are $log user loged in right now"
Output :-
There are 49 users in network
There are 2 user loged in right now
steps for dual boot installation (How To Install Ubuntu18.04 LTS Alongside Windows 10)
In the Disk Management tool, right click on the drive which you want to partition and
select shrink volume. In my case, I shrank the C drive to make some free space:
Or if you have free space in your drive make it is not a window drive then delete particular volume
You can leave the free space as it is. We shall use it while installing Ubuntu.
This is the most important step. The new secure boot feature of Windows 8, originally intended
for security feature for root kit viruses, prevents dual booting of Windows with Linux. To dual
boot Windows 8 with Linux, we must disable secure boot in UEFI.
you have booted in the live USB, you will be presented with option to try or install Ubuntu.
You can also boot from any bootable media now you are entering in installation steps of ubuntu
you will first be asked to select your keyboard layout After selecting Continue you will be
asked What apps would you like to install to start with?
o The two options are ‘Normal installation’ and ‘Minimal installation’.
The first is the equivalent to the old default bundle of utilities, applications, games and media
players — a great launchpad for any Linux installation.
The second takes considerably less storage space and allows you to install only what you need.
Beneath the installation-type question are two checkboxes; one to enable updates while
installing and another to enable third-party software.
We advise enabling both Download updates and Install third-party software.
Stay connected to the internet so you can get the latest updates while you install Ubuntu.
If you are not connected to the internet, you will be asked to select a wireless network, if available.
We advise you to connect during the installation so we can ensure your machine is up to date
Remember we had created some free space beforehand? We shall use the free space to create
Root, Swap and Home. Select the free space and click on the + sign to create partition .
It will provide you with option to create Linux partition. We are creating the Root partition. Any
thing above 20 GB is more than sufficient for it. Choose the size, select Ext 4 as file type and /
(means root) as the mount point.there basic three partition root , boot and swap area
Clicking on OK in previous step will bring you to the partition screen. Next we will create swap.
Like previously, click on the + sign again. This time use the file type as Swap area. Suggestible
swap size is double of RAM
In similar fashion, boot and then create a Home partition. Allocate it maximum space (in fact
allocate it rest of the free space) because this is where you’ll save music, pictures and
downloaded files.
Once you are ready with Root, Swap and Home, click on Install Now:
Screen :
Terminal:
GUI:
Install additional applications
An application is software that has a graphical user interface (GUI). The Ubuntu development
team has chosen a default set of applications that we think makes Ubuntu very useful for most
day-to-day tasks. However, you will certainly want to install more applications to make
Ubuntu more useful to you. To install an application, you can use Ubuntu Software.
Applications are available in two formats: snap packages and Debian packages. An application
available as a snap package is from now on referred to as a snap. Some applications are
available in both formats. In such a case in Ubuntu Software the snap will be listed first.
You may also wish to install software that does not have a GUI. To install such software, you
can use Synaptic. Note that Synaptic does not list snaps.
To install an application:
1. Click the Ubuntu Software icon in the Dock, or search for Software in the Activities search bar.
2. When Ubuntu Software launches, search for an application, or select a category and find an
application from the list.
3. Select the application that you want to install and click Install.
4. You will be asked to authenticate by entering your password. Once you have done that the
installation will begin. The installation usually finishes quickly, but could take a while if you have a
slow Internet connection.
To Remove an application
An application is software that has a graphical user interface (GUI). You can use Ubuntu
Software to remove applications that you no longer use.
Applications are available in two formats: snap packages and Debian packages. An application
available as a snap package is from now on referred to as a snap. Some applications are
available in both formats. In such a case in Ubuntu Software the snap will be listed first.
You may also wish to remove software that does not have a GUI. To remove such software,
you can use Synaptic. Note that Synaptic does not list snaps.
To remove an application:
1. Click the Ubuntu Software icon in the Dock, or search for Software in the Activities search bar.
2. When Ubuntu Software opens, click the Installed button at the top.
3. Find the application that you want to remove by using the search box or by looking through
the list of installed applications.
4. Select the application and click Remove.
5. Confirm that you want to remove the application.
6. You will be asked to authenticate by entering your password. After you have done that, the
application will be removed.
In the Anonymous mode, remote clients can access the FTP server by using the default user account
called “anonymous” or “ftp” and sending an email address as the password.
In the Authenticated mode a user must have an account and a password. This latter choice is very
insecure and should not be used except in special circumstances. If you are looking to transfer files
securely see SFTP in the section on OpenSSH-Server.
User access to the FTP server directories and files is dependent on the permissions defined for the
account used at login. As a general rule, the FTP daemon will hide the root directory of the FTP server and
change it to the FTP Home directory. This hides the rest of the file system from remote sessions.
anonymous_enable=YES
During installation a ftp user is created with a home directory of /srv/ftp. This is the
default FTP directory.
If you wish to change this location, to /srv/files/ftp for example, simply create a directory
in another location and change the ftp user’s home directory:
write_enable=YES
Now restart vsftpd:
anon_upload_enable=YES
A very useful package for testing and troubleshooting DNS issues is the dnsutils package. Very often these tools
will be installed already, but to check and/or install dnsutils enter the following:
sudo apt install dnsutils
Configuration
There are many ways to configure BIND9. Some of the most common configurations are a caching nameserver,
primary server, and secondary server.
When configured as a caching nameserver BIND9 will find the answer to name queries and remember
the answer when the domain is queried again.
As a primary server, BIND9 reads the data for a zone from a file on its host and is authoritative for that
zone.
As a secondary server, BIND9 gets the zone data from another nameserver that is authoritative for the
zone.
Overview
The DNS configuration files are stored in the /etc/bind directory. The primary configuration file
is /etc/bind/named.conf, which in the layout provided by the package just includes these files.
/etc/bind/named.conf.options: global DNS options
/etc/bind/named.conf.local: for your zones
/etc/bind/named.conf.default-zones: default zones such as localhost, its reverse, and the root hints
Caching Nameserver
The default configuration acts as a caching server. Simply uncomment and edit /etc/bind/named.conf.options to
set the IP addresses of your ISP’s DNS servers
Primary Server
In this section BIND9 will be configured as the Primary server for the domain example.com. Simply
replace example.com with your FQDN (Fully Qualified Domain Name).
Secondary Server
Once a Primary Server has been configured a Secondary Server is highly recommended in order to maintain the
availability of the domain should the Primary become unavailable.
First, on the Primary server, the zone transfer needs to be allowed. Add the allow-transfer option to the example
Forward and Reverse zone definitions in /etc/bind/named.conf.local
Ubuntu includes its own firewall, known as ufw – short for “uncomplicated firewall.” Ufw is an easier-to-
use frontend for the standard Linux iptables commands. You can even control ufw from a graphical
interface.
Ubuntu’s firewall is designed as an easy way to perform basic firewall tasks without learning iptables. It
doesn’t offer all the power of the standard iptables commands, but it’s less complex.
Terminal Usage
The firewall is disabled by default. To enable the firewall, run the following command from a terminal:
You don’t necessarily have to enable the firewall first. You can add rules while the firewall is offline, and
then enable it after you’re done configuring it.
UFW is a graphical interface for ufw. Ubuntu doesn’t come with a graphical interface, but
gufw is included in Ubuntu’s software repositories. You can install it with the following
command:
GUFW appears in the Dash as an application named Firewall Configuration. Like ufw itself,
GUFW provides a simple, easy-to-use interface. You can easily enable or disable the
firewall, control the default policy for inbound or outbound traffic, and add rules.
The rules editor can be used to add simple rules or more complicated ones.
Remember, you can’t do everything with ufw – for more complicated firewall tasks, you’ll
have to get your hands dirty with iptables.
A Web server is a software responsible for accepting HTTP requests from clients, which
are known as Web browsers, and serving them HTTP responses along with optional data
contents, which usually are Web pages such as HTML documents and linked objects
(images, etc.).
Apache is the most commonly used Web server on Linux systems. Web servers are used to
serve Web pages requested by client computers. Clients typically request and view Web
pages using Web browser applications such as Firefox, Opera, Chromium, or Internet
Explorer.
Users enter a Uniform Resource Locator (URL) to point to a Web server by means of its
Fully Qualified Domain Name (FQDN) and a path to the required resource. For example, to
view the home page of the Ubuntu Web site a user will enter only the FQDN:
www.ubuntu.com
To view the community sub-page, a user will enter the FQDN followed by a path:
www.ubuntu.com/community
The most common protocol used to transfer Web pages is the Hyper Text Transfer Protocol (HTTP).
Protocols such as Hyper Text Transfer Protocol over Secure Sockets Layer (HTTPS), and File Transfer
Protocol (FTP), a protocol for uploading and downloading files, are also supported.
Installation
The Apache2 web server is available in Ubuntu Linux. To install Apache2:
At a terminal prompt enter the following command:
Configuration
Apache2 is configured by placing directives in plain text configuration files. These directives are separated
between the following files and directories:
1. apache2.conf: the main Apache2 configuration file. Contains settings that are global to Apache2.
2. httpd.conf: historically the main Apache2 configuration file, named after the httpd daemon. Now the file
does not exist. In older versions of Ubuntu the file might be present, but empty, as all configuration
options have been moved to the below referenced directories.
3. conf-available: this directory contains available configuration files. All files that were previously
in /etc/apache2/conf.d should be moved to /etc/apache2/conf-available.
4. conf-enabled: holds symlinks to the files in /etc/apache2/conf-available. When a configuration file is
symlinked, it will be enabled the next time apache2 is restarted.
6. mods-available: this directory contains configuration files to both load modules and configure them. Not
all modules will have specific configuration files, however.
8. ports.conf: houses the directives that determine which TCP ports Apache2 is listening on.
9. sites-available: this directory has configuration files for Apache2 Virtual Hosts. Virtual Hosts allow Apache2
to be configured for multiple sites that have separate configurations
.
10. sites-enabled: like mods-enabled, sites-enabled contains symlinks to the /etc/apache2/sites-
available directory. Similarly when a configuration file in sites-available is symlinked, the site configured by
it will be active once Apache2 is restarted.
A- Apache
M-MySQL
P-phpmyadmin
This section of the Ubuntu Server Guide introduces principles and tools used in configuring your Ubuntu
Server for sharing network resources with Windows computers
Successfully networking your Ubuntu system with Windows clients involves providing and integrating
with services common to Windows environments. Such services assist the sharing of data and
information about the computers and users involved in the network, and may be classified under three
major categories of functionality:
1. File and Printer Sharing Services. Using the Server Message Block (SMB) protocol to facilitate the sharing
of files, folders, volumes, and the sharing of printers throughout the network.
2. Directory Services. Sharing vital information about the computers and users of the network with such
technologies as the Lightweight Directory Access Protocol (LDAP) and Microsoft Active Directory®.
3. Authentication and Access. Establishing the identity of a computer or user of the network and
determining the information the computer or user is authorized to access using such principles and
technologies as file permissions, group policies, and the Kerberos authentication service.
File Server
One of the most common ways to network Ubuntu and Windows computers is to configure Samba as a
File Server. This section covers setting up a Samba server to share files with Windows clients.
Installation
The first step is to install the samba package. From a terminal prompt enter:
Configuration
The main Samba configuration file is located in /etc/samba/smb.conf. The default configuration file has a
significant number of comments in order to document various configuration directives.
1. First, edit the following key/value pairs in the [global] section of /etc/samba/smb.conf:
workgroup = EXAMPLE
...
security = user
The security parameter is farther down in the [global] section, and is commented by default. Also,
change EXAMPLE to better match your environment.
2. Create a new section at the bottom of the file, or uncomment one of the examples, for the directory to be
shared:
[share]
comment = Ubuntu File Server Share
path = /srv/samba/share
browsable = yes[OK TO YES FOR PRINTER]
3.Now that Samba is configured, the directory needs to be created and the permissions changed. From a
terminal enter:
sudo mkdir -p /srv/samba/share
sudo chown nobody:nogroup /srv/samba/share/
From a Windows client you should now be able to browse to the Ubuntu file server and see the
shared directory. If your client doesn't show your share automatically, try to access your server by
its IP address, e.g. \\192.168.1.1 OR 127.0.0.1 , in a Windows Explorer window. To check
that everything is working try creating a directory from Windows.
To create additional shares simply create new [dir] sections in /etc/samba/smb.conf, and
restart Samba. Just make sure that the directory you want to share actually exists and the
permissions are correct.
This article will help you to install Wine 1.7.38 Development Release on RHEL based systems.
For ubuntu you have to use “apt-get “
Installing Prerequisite
Wine required many development packages, So we need to install required packages for Wine using yum
package manager using following commands.
Install Wine
RPM packages for wine are not available for latest versions, So we need to download wine source code.
Use below commands to download it.
# cd /usr/src
# wget http://prdownloads.sourceforge.net/wine/wine-1.7.38.tar.bz2
# cd wine-1.7.38
Configure wine using one of following command based on your system architecture.
# ./configure
# ./configure --enable-win64
# make
# make install
On 32-Bit Systems:
# wine --version
On 64-Bit Systems:
# wine64 –version
To use wine we need to login on GUI desktop. After that Download a windows executable (.exe) file
like PuTTY on your system and open it with Wine as below screenshot or use following command.
# wine putty.exe
Virtual machine can offer an instruction set architecture that differs from real
computer.
Easy maintenance, application provisioning, availability and convenient recovery.
VM Dis-advantages:
When multiple virtual machines are simultaneously running on a host computer,
each virtual machine may introduce an unstable performance, which depends on the
workload on the system by other running virtual machines.
Virtual machine is not that much efficient as a real one when accessing the hardware.
Virtual Machine isolates the hardware of our computer such as CPU, hard drives,
memory, NIC (Network Interface Card) etc, into many different execution
environments as per our requirements, feel like a single computer.
Examples: VirtualBox, VMWare Workstation & Microsoft Hyper-V.