You are on page 1of 50

Introduction to Linux operating system

Introduction and Types of operating system


An operating system acts as an intermediary between the user of a computer and computer
hardware. The purpose of an operating system is to provide an environment in which a user can
execute programs in a convenient and efficient manner.
An operating system is software that manages the computer hardware. The hardware must
provide appropriate mechanisms to ensure the correct operation of the computer system and to
prevent user programs from interfering with the proper operation of the system.
Operating System – Definition:
 An operating system is a program that controls the execution of application programs and
acts as an interface between the user of a computer and the computer hardware.
 A more common definition is that the operating system is the one program running at all
times on the computer (usually called the kernel), with all else being application programs.
 An operating system is concerned with the allocation of resources and services, such as
memory, processors, devices and information. The operating system correspondingly
includes programs to manage these resources, such as a traffic controller, a scheduler,
memory management module, I/O programs, and a file system.
Functions of Operating system – Operating system performs three functions:
1. Convenience: An OS makes a computer more convenient to use.
2. Efficiency: An OS allows the computer system resources to be used in an efficient manner.
3. Ability to Evolve: An OS should be constructed in such a way as to permit the effective
development, testing and introduction of new system functions without at the same time
interfering with service.
Operating system as User Interface –
1. User
2. System and application programs
3. Operating system
4. Hardware
Every general purpose computer consists of the hardware, operating system, system programs,
and application programs. The hardware consists of memory, CPU, ALU, and I/O devices,
peripheral device and storage device. System program consists of compilers, loaders, editors, OS
etc. The application program consists of business programs, database programs.
Fig1: Conceptual view of a computer system
Every computer must have an operating system to run other programs. The operating system
coordinates the use of the hardware among the various system programs and application
programs for a various users. It simply provides an environment within which other programs
can do useful work.
The operating system is a set of special programs that run on a computer system that allows it to
work properly. It performs basic tasks such as recognizing input from the keyboard, keeping
track of files and directories on the disk, sending output to the display screen and controlling
peripheraldevices.
OS is designed to serve two basic purposes:
1. It controls the allocation and use of the computing System’s resources among the various
user and tasks.
2. It provides an interface between the computer hardware and the programmer that simplifies
and makes feasible for coding, creation, debugging of application programs.
The Operating system must support the following tasks. The task are:
1. Provides the facilities to create, modification of programs and data files using an editor.
2. Access to the compiler for translating the user program from high level language to
machine language.
3. Provide a loader program to move the compiled program code to the computer’s memory
for execution.
4. Provide routines that handle the details of I/O programming.
I/O System Management –
The module that keeps track of the status of devices is called the I/O traffic controller. Each I/O
device has a device handler that resides in a separate process associated with that device.
The I/O subsystem consists of
 A memory Management component that includes buffering caching and spooling.
 A general device driver interface.
Drivers for specific hardware devices.
Assembler –
Input to an assembler is an assembly language program. Output is an object program plus
information that enables the loader to prepare the object program for execution. At one time, the
computer programmer had at his disposal a basic machine that interpreted, through hardware,
certain fundamental instructions. He would program this computer by writing a series of ones
and Zeros (Machine language), place them into the memory of the machine.
Compiler –
The High level languages- examples are FORTRAN, COBAL, ALGOL and PL/I are processed
by compilers and interpreters. A compiler is a program that accepts a source program in a “high-
level language “and produces a corresponding object program. An interpreter is a program that
appears to execute a source program as if it was machine language. The same name (FORTRAN,
COBAL etc.) is often used designate both a compiler and its associated language.
Loader –
A Loader is a routine that loads an object program and prepares it for execution. There are
various loading schemes: absolute, relocating and direct-linking. In general, the loader must load,
relocate and link the object program. Loader is a program that places programs into memory and
prepares them for execution. In a simple loading scheme, the assembler outputs the machine
language translation of a program on a secondary devices and a loader is places in core. The
loader places into memory the machine language version of the user’s program and transfers
control to it. Since the loader program is much smaller than the assembler, those makes more
core available to user’s program.
History of Operating system –
Operating system has been evolving through the years. Following Table shows the history of OS.
ELECTRONIC

GENERATION YEAR DEVICE USED TYPES OF OS DEVICE

1945-

First 55 Vaccum Tubes Plug Boards

1955-

Secondt 65 Transistors Batch Systems

1965- Integerated

Third 80 Circuits(IC) Multiprogramming


Since Large Scale

Fourth 1980 Integration PC

Types of Operating System –


 Batch Operating System- Sequence of jobs in a program on a computer without manual
interventions.
 Time sharing operating System- allows many users to share the computer resources.(Max
utilization of the resources).
 Distributed operating System- Manages a group of different computers and make appear to
be a single computer.
 Network operating system- computers running in different operating system can participate
in common network (It is used for security purpose).
 Real time operating system – meant applications to fix the deadlines.
Examples of Operating System are –
 Windows (GUI based, PC)
 GNU/Linux (Personal, Workstations, ISP, File and print server, Three-tier client/Server)
 macOS (Macintosh), used for Apple’s personal computers and work stations (MacBook,
iMac).
 Android (Google’s Operating System for smartphones/tablets/smartwatches)
 iOS (Apple’s OS for iPhone, iPad and iPod Touch)

Linux operating system


Linux is an OS, but it is actually not. Linux itself doesn’t form an OS. Linux is nothing but a
Kernel.

Kernel is a large code of millions of lines, which forms the core of any operating system. It can
be considered as a resource manager of an operating system. User applications can communicate
with the hardware only through the kernel. It is the kernel which keeps the OS up and running.

Linux kernel based operating systems are called Linux OS, like redhat, Linux mint, Ubuntu,
centos etc.

History of Linux
UNIX is considered as the very first operating system of all its characteristics. Before UNIX
there was no operating system concept. UNIX was developed by the employees of AT&T Bell
Laboratories) in 1969
UNIX was not a free OS; also the OS was not available for common users. Actually at that time
there was no personal computer concept. So the operating system was mainly used in mainframe
computers and for research purposes.

There was a research student’s version of UNIX called Minix released in the year 1987. The
source code of the Minix was available, but modifications were not allowed.

Linus Torvalds from the University of Helsinki was doing a personal project in which he tried to
modify the kernel of Minix and develop a new one of his own. He was using Minix since his
school days. He posted on the internet that he is trying to develop the kernel for a new operating
system. So many brains around globe respond to this and contribute their code. Linus Torvalds
coordinate all these and formed Linux kernel in the year 1991.

The Free Software Foundation (FSF) started by Richard Stallman in the year 1983, was running
a project called GNU (Gnu Not Unix). They had the entire user interface ready, but their kernel
was a complete failure. They used the Linux kernel developed by Linus Torvalds for their GNU
project and formed GNU/Linux.

FSF licensed the operating system GNU/Linux under GPL (General Public License) in the year
1992. The OS is available for free. It was open source, which means the source code is available.
Anyone can modify the source code and develop their version of OS. But GPL doesn’t allow
common people to distribute their modified Linux OS; all the modified versions should be
submitted back to the FSF.
History of Linux

Windows Vs Linux

Windows vsLinux
Linux Windows
Free Operating System Windows is not available for free
Linux is open source Windows is not open source
Linux is highly secure Windows have so many security issues
Multiple user interface Single user interface
Multiuser multitasking Single user multitasking
Little chance for a system halt Windows suffer from system halt occasionally
We can configure hardware through files We can only install drivers for hardware
Linux properties
1) Free OS
Linux is a free operating system. You can just search the internet and download the OS version
you like.
2) Open source
Open source means the source code is available for reference and modification. Nothing is
hidden in the Linux.
3) Security
Linux is a highly secure OS. Ever wonder why people say that virus won’t affect Linux? The
main reason behind this is nothing but most of the hackers support the open source Linux. Also,
- No registry concept like windows
In windows there is a file called registry file, in which all the configurations are maintained.
Normal people can’t read the registry file, because the data are stored in hex values. Those who
know how to modify this registry file can create a virus in windows.
- Unlike windows not even a single program run without the permission of the
administrator.
- Windows can have many users having administrating power. So there is a potential threat
of unauthorized access by an administrator into another administrator’s documents or
applications.
- Most of the virus comes in .exe format. Linux is safe from that kind of virus files, because
it does not support .exe files.
Virus attack does affect Linux also, but their intensity is limited to like, hacking administrator
password and similar things.
4) Multiple user interfaces
Windows has only one user interface, GUI. Command prompt is simply an application runs in
GUI. But Linux has two kinds of user interfaces
- One GUI ( Graphical User Interface )
- Six TUIs ( Text User Interface )
5) Multiuser Multitasking
Windows allows only a single user to login at a time and do the work. But in Linux more than
one user can login at any given time and each user can perform multiple tasks simultaneously.
6) Linux seldom crash
There is little chance for a system halt in Linux. Even if some applications crash, we can just kill
those particular applications only. The whole system won’t go down due to such kind of issues.
But in windows if a single program is not responding, we can use task manager and most of the
cases it won’t work out and finally we have to restart the system. That is why Linux is preferred
for network servers which require running 24*7 without any interruption.
7) Linux treat everything as files
Unlike windows, Linux treats everything as files including hardware devices. So we can
configure the hardware devices through these files. In windows our access to the hardware is
very much limited; we can do nothing but install the specific drivers.
Linux allows to write drivers for the hardware, and thus engineers prefer Linux for device driver
coding.

File system in Linux

Filesystem in Linux
In a computer the hard disk forms a physical medium which can store files, and thus forms a
filesystem. The major filesystem types in Linux are
1) EXT3
2) EXT4
3) VFAT
4) Swap
Ext3 and Ext4 stands for extended file system. VFAT is a filesystem equivalent to the windows
FAT ( File Allocation Table ) file system, it stands for Virtual FAT.

Ext3 and Ext4 are used to create and access logical volume. VFAT is used in external medias
like Pendrive and all.

Swap is used to create a swap area in the hard disk, which can be used as a virtual memory. The
total memory which a running application can see is the sum of physical memory ( RAM ) and
the Virtual memory ( Swap ).

Mount points in Linux


The windows use a method called “Drive letter mounting” to access the disc space. Windows
users are familiar with the terms C-drive, D-drive etc. But Linux use an entirely different
technique called “mount point”.
Unlike windows we can see the mounted disk space as folders under the root of the file system.
In windows we can see them as drives.
Examples of mount points are /, /boot, /home etc.
Filesystem hierarchy in Linux
In Linux the file system is maintained in a hierachial method. The “/” forms the root of all
filesystem, under which all other directories are mounted.

Filesystem hierarchy in Linux

Mount points and their Usage


Directory Usage
/bin Binary directory; Stores commands used in Linux
/boot Store files like boot loader, required during boot time
/dev Device information directory. Device files are kept here
/etc System configuration files are stored here
/home Document directory of all normal users
/root Document directory of super-user
/mnt Mount directory for manual mounting
/media Auto-mount directory
/lib Shared libraries and kernel modules are stored here
/lost + found Back-up point for ext3 file system
/proc Process information directory. It provides interface to kernel data structures
/tmp Directory provided for storing temporary files
/sbin Directory for storing only default system commands
/var Varying file directory for storing regularly updating files
/opt Optional directory for installing additional software

In practical cases, there could be more mount points than give in the above list

User types in linux


Linux has three types of users
1) Super-user
2) Normal-user
3) System user
Super-user in Linux is called “root”. Root user has complete previlage in Linux. Only he has the
administratory power.

Normal user doesn't have administrator power. Normal users have only a limited access. It is the
root user which creates the normal user. In certain Linux OS there is no root user, like in
Ubuntu, Linuxmint etc. In such cases we can use commands to give normal user an
administrative privilage.

System users are the users created by applications in the system. For example in servers the
application allows only authorised users to access its service.

Features
Following are some of the important features of Linux Operating System.

 Portable − Portability means software can works on different types of hardware in same
way. Linux kernel and application programs supports their installation on any kind of
hardware platform.
 Open Source − Linux source code is freely available and it is community based
development project. Multiple teams work in collaboration to enhance the capability of
Linux operating system and it is continuously evolving.

 Multi-User − Linux is a multiuser system means multiple users can access system
resources like memory/ ram/ application programs at same time.

 Multiprogramming − Linux is a multiprogramming system means multiple applications


can run at same time.

 Hierarchical File System − Linux provides a standard file structure in which system
files/ user files are arranged.

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

 Security − Linux provides user security using authentication features like password
protection/ controlled access to specific files/ encryption of data.

Architecture of Linux OS and shell interface


Linux is one of popular version of UNIX operating System. It is open source as its source code
is freely available. It is free to use. Linux was designed considering UNIX compatibility. Its
functionality list is quite similar to that of UNIX.

Components of Linux System


Linux Operating System has primarily three components

 Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this
operating system. It consists of various modules and it interacts directly with the
underlying hardware. Kernel provides the required abstraction to hide low level
hardware details to system or application programs.

 System Library − System libraries are special functions or programs using which
application programs or system utilities accesses Kernel's features. These libraries
implement most of the functionalities of the operating system and do not requires kernel
module's code access rights.
 System Utility − System Utility programs are responsible to do specialized, individual
level tasks.

Kernel Mode vs User Mode


Kernel component code executes in a special privileged mode called kernel mode with full
access to all resources of the computer. This code represents a single process, executes in single
address space and do not require any context switch and hence is very efficient and fast. Kernel
runs each processes and provides system services to processes, provides protected access to
hardware to processes.

Support code which is not required to run in kernel mode is in System Library. User programs
and other system programs works in User Mode which has no access to system hardware and
kernel code. User programs/ utilities use System libraries to access Kernel functions to get
system's low level tasks.

Architecture
The following illustration shows the architecture of a Linux system −
The architecture of a Linux System consists of the following layers −

 Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).

 Kernel − It is the core component of Operating System, interacts directly with hardware,
provides low level services to upper layer components.

 Shell − An interface to kernel, hiding complexity of kernel's functions from users. The
shell takes commands from the user and executes kernel's functions.

 Utilities − Utility programs that provide the user most of the functionalities of an
operating systems.
Shell interface

If you are using any major operating system you are indirectly interacting to shell. If you are
running Ubuntu, Linux Mint or any other Linux distribution, you are interacting to shell every
time you use terminal. In this article I will discuss about linux shells and shell scripting so before
understanding shell scripting we have to get familiar with following terminologies –
 Kernel
 Shell
 Terminal
The kernel is a computer program that is the core of a computer’s operating system, with
complete control over everything in the system. It manages following resources of the Linux
system –
 File management
 Process management
 I/O management
 Memory management
 Device management etc.
It is often mistaken that Linus Torvalds has developed Linux OS, but actually he is only
responsible for development of Linux kernel.
Complete Linux system = Kernel + GNU system utilities and libraries + other management
scripts + installation scripts.

A shell is special user program which provide an interface to user to use operating system
services. Shell accept human readable commands from user and convert them into something
which kernel can understand. It is a command language interpreter that execute commands read
from input devices such as keyboards or from files. The shell gets started when the user logs in
or start the terminal.

linux shell

Shell is broadly classified into two categories –


 Command Line Shell
 Graphical shell
Command Line Shell
Shell can be accessed by user using a command line interface. A special program
called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in
the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is
then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –
linux command line

In above screenshot “ls” command with “-l” option is executed.


It will list all the files in current working directory in long listing format.
Working with command line shell is bit difficult for the beginners because it’s hard to memorize
so many commands. It is very powerful, it allows user to store commands in a file and execute
them together. This way any repetitive task can be easily automated. These files are usually
called batch files in Windows and Shell Scripts in Linux/macOS systems.
Graphical Shells
Graphical shells provide means for manipulating programs based on graphical user interface
(GUI), by allowing for operations such as opening, closing, moving and resizing windows, as
well as switching focus between windows. Window OS or Ubuntu OS can be considered as good
example which provide GUI to user for interacting with program. User do not need to type in
command for every actions.A typical GUI in Ubuntu system –
GUI shell

There are several shells are available for Linux systems like –
 BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as
default login shell in Linux systems and in macOS. It can also be installed on Windows
OS.
 CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming
language.
 KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard
specifications etc.
Each shell does the same job but understand different commands and provide different built in
functions.
Shell Scripting
Usually shells are interactive that mean, they accept command as input from users and execute
them. However some time we want to execute a bunch of commands routinely, so we have type
in all commands each time in terminal.
As shell can also take commands as input from file we can write these commands in a file and
can execute them in shell to avoid this repetitive work. These files are called Shell
Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell
script is saved with .sh file extension eg. myscript.sh

A shell script have syntax just like any other programming language. If you have any prior
experience with any programming language like Python, C/C++ etc. it would be very easy to get
started with it.
A shell script comprises following elements –
 Shell Keywords – if, else, break etc.
 Shell commands – cd, ls, echo, pwd, touch etc.
 Functions
 Control flow – if..then..else, case and shell loops etc.
Why do we need shell scripts
There are many reasons to write shell scripts –
 To avoid repetitive work and automation
 System admins use shell scripting for routine backups
 System monitoring
 Adding new functionality to the shell etc.
Advantages of shell scripts
 The command and syntax are exactly the same as those directly entered in command line,
so programmer do not need to switch to entirely different syntax
 Writing shell scripts are much quicker
 Quick start
 Interactive debugging etc.
Disadvantages of shell scripts
 Prone to costly errors, a single mistake can change the command which might be harmful
 Slow execution speed
 Design flaws within the language syntax or implementation
 Not well suited for large and complex task
 Provide minimal data structure unlike other scripting languages. etc
Simple demo of shell scripting using Bash Shell
If you work on terminal, something you traverse deep down in directories. Then for coming few
directories up in path we have to execute command like this as shown below to get to the
“python” directory –

It is quite frustrating, so why not we can have a utility where we just have to type the name of
directory and we can directly jump to that without executing “cd ../” command again and again.
Save the script as “jump.sh”

Linux system calls


A system call is the programmatic way in which a computer program requests a service from
the kernel of the operating system it is executed on. A system call is a way for programs
to interact with the operating system. A computer program makes a system call when it makes
a request to the operating system’s kernel. System call provides the services of the operating
system to the user programs via Application Program Interface(API). It provides an interface
between a process and operating system to allow user-level processes to request services of the
operating system. System calls are the only entry points into the kernel system. All programs
needing resources must use system calls.
Services Provided by System Calls :
1. Process creation and management
2. Main memory management
3. File Access, Directory and File system management
4. Device handling(I/O)
5. Protection
6. Networking, etc.
Types of System Calls : There are 5 different categories of system calls –
1. Process control: end, abort, create, terminate, allocate and free memory.
2. File management: create, open, close, delete, read file etc.
3. Device management
4. Information maintenance
5. Communication
Examples of Windows and Unix System Calls –
WINDOWS UNIX

CreateProcess() fork()

ExitProcess() exit()

Process Control WaitForSingleObject() wait()

CreateFile() open()

ReadFile() read()

WriteFile() write()

CloseHandle() close()
File Manipulation

SetConsoleMode() ioctl()

Device ReadConsole() read()

Manipulation WriteConsole() write()


GetCurrentProcessID() getpid()

Information SetTimer() alarm()

Maintenance Sleep() sleep()

CreatePipe() pipe()

CreateFileMapping() shmget()

Communication MapViewOfFile() mmap()

SetFileSecurity() chmod()

InitlializeSecurityDescriptor() umask()

Protection SetSecurityDescriptorGroup() chown()

Linux shared memory management

Though virtual memory and demand paging are the building blocks of the Linux memory
management system, there are various other concepts that make Linux memory management
very powerful.

I. Linux Swapping

Suppose there is a situation where a process needs to have one of its virtual page into the
physical memory but the physical memory has no room for any more pages to be brought in.

Well, the OS will have to manage this situation by allowing this page to be in physical memory.
But for this to happen, a page already residing in physical memory needs to be discarded.

Now, if the page to be discarded is from an executable image or data file and the page has not
been written to, then it can easily be discarded as whenever required, the same page can easily be
brought back into physical memory from the same executable image or data file.
But lets suppose the page which the OS is going to discard is the one which has been written to,
then this kind of page is known as a dirty page.

A dirty page has to be preserved so as to be used at some later stage. When dirty pages are
discarded from physical memory then they are saved in a special file known as swap files. This is
known as swapping.
The time taken to access a swap page is quite substantial if compared to speed of processor.

So we see that OS should have a good swapping algorithm in order to decide on discarding vs
swapping. An inefficient swap algorithm may lead to a phenomenon where-in the OS gets so
busy in swapping files and then again reading back to physical memory that its actually devotes
very less time to the real work that processes demand. This phenomenon is known as thrashing.
Also, A set of pages that a process is continuously using is known as working set . A good swap
algorithm would rarely let the OS get into thrashing and would also make sure that working set
of all the processes is always there in the physical memory.

Linux decides on which pages are to be kept in the memory and which pages are to removed
using a scheme of ‘Least recently used‘.
In this scheme, each page in physical memory has an age associated with it. The age changes
with the fact that the page is being accessed or not. If the page is being frequently accessed then
that page is supposed to be quite young in age while if a page is not being accessed than that
page becomes older. The older age pages are proffered to be swapped/discarded from physical
memory.

II. Caches

In order to extract the most out of system, fast processors and operating systems are being
developed. Though this is good but one aspect which makes the processor , operating system and
their interaction faster is the concept of caches.

Some of the important caches in Linux are described below.


1. Linux Swap Cache

As already discussed above, only dirty pages are swapped as we need to retain the pages that
have been modified. Also, suppose if a page was modified and was swapped, now if the same
page was brought back into physical memory and now there is a need to swap it again but the
page has not been modified any further then there is no need to swap this page. Just discard it as
this version of the page is already there in the swap file. This saves a good amount of time which
otherwise would have been wasted.

Now to implement the above concept, Linux makes use of swap cache.

 A swap cache is nothing but a list of page table entries with one entry per physical page.
 Each entry corresponds to a swapped out page along with the information about the swap file
in which the page is being held along with its exact location in the swap file.
 If any page table entry in swap cache is non-zero then it represents a page that is being held
in a swap file and that page has not been modified any further.
 If a page has its entry in the swap cache and is further modified then its entry from swap
cache is removed.
 This way the cache contains information only on those pages that are not modified since they
were last swapped.
So we see that swap cache helps a lot in increasing the efficiency of swapping mechanism.

2. Hardware Cache

As we have already discussed in previous article that a processor reads page table entries to
convert virtual address to physical address. Usually a processor stores the information of page
table entries in a hardware cache.
This hardware cache consists of Translational look-aside buffers or TLBs.
Whenever a processor needs to translate a virtual address, then it tries to fetch the page table
entry information from TLBs. If it finds the entry then it proceeds further but if processor is not
able to find any such entry then it tells the OS that a TLB miss has occurred and asks the OS to
fix things up.
To deliver this information of TLB miss to OS, some kind of exception mechanism is used
which is processor dependent. Now, the OS finds the correct entry and updates the TLB entry
with it. When the exception is cleared (after OS fixes the problem) then the processor again tries
to search the TLBs for the entry and this time it finds a valid entry.

3. Linux Buffer Cache

A buffer cache contains data buffers that the block device drivers use.

A block device driver is a one that operates on block of data i.e. it can be accessed by reading or
writing fixed chunks or blocks of data. A buffer cache is indexed. The device identifier is used
for the indexing purpose.

The buffer cache makes the reading/writing very efficient and fast. For example consider a
block device for example a hard disk. Reading/writing a hard disk requires file I/O which is quite
expensive if we do it on hard disk each time a read or write is done. This buffer cache which sits
in between, saves time as reads and write are done on this and rest is taken care by the cache.
To view swap, memory, page, block IO, traps, disks and cpu activity, you can use tools
like vmstat or sar.

III. Shared Virtual memory

When code is written then great care is taken by the developers that no piece of code is
unnecessarily repeated. For example, functions are used in programs so that same piece of code
can be called anytime from within the code.

A group of functions which can be commonly used are clubbed up into libraries. There-in comes
the concept of shared memory which is once loaded into memory and can be used by multiple
processes.

Virtual memory makes it easy for processes to share memory this is because the physical
address are mapped through page tables and this is very much possible that same physical page
frame number could be mapped in page table of multiple processes. This concept is known
as shared virtual memory.

Device and Disk management in Linux

An Operating System (OS) is an interface between a computer user and computer hardware. An
operating system is a software which performs all the basic tasks like file management, memory
management, process management, handling input and output, and controlling peripheral
devices such as disk drives and printers.

Some popular Operating Systems include Linux, Windows, OS X, VMS, OS/400, AIX, z/OS,
etc.

Definition
An operating system is a program that acts as an interface between the user and the computer
hardware and controls the execution of all kinds of programs.

Following are some of important functions of an operating System.

 Memory Management
 Processor Management
 Device Management
 File Management
 Security
 Control over system performance
 Job accounting
 Error detecting aids
 Coordination between other software and users
Memory Management
Memory management refers to management of Primary Memory or Main Memory. Main
memory is a large array of words or bytes where each word or byte has its own address.

Main memory provides a fast storage that can be accessed directly by the CPU. For a program
to be executed, it must in the main memory. An Operating System does the following activities
for memory management −

 Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are
not in use.

 In multiprogramming, the OS decides which process will get memory when and how
much.

 Allocates the memory when a process requests it to do so.

 De-allocates the memory when a process no longer needs it or has been terminated.

Processor Management
In multiprogramming environment, the OS decides which process gets the processor when and
for how much time. This function is called process scheduling. An Operating System does the
following activities for processor management −

 Keeps tracks of processor and status of process. The program responsible for this task is
known as traffic controller.

 Allocates the processor (CPU) to a process.

 De-allocates processor when a process is no longer required.

Device Management
An Operating System manages device communication via their respective drivers. It does the
following activities for device management −
 Keeps tracks of all devices. Program responsible for this task is known as the I/O
controller.

 Decides which process gets the device when and for how much time.

 Allocates the device in the efficient way.

 De-allocates devices.

File Management
A file system is normally organized into directories for easy navigation and usage. These
directories may contain files and other directions.

An Operating System does the following activities for file management −

 Keeps track of information, location, uses, status etc. The collective facilities are often
known as file system.

 Decides who gets the resources.

 Allocates the resources.

 De-allocates the resources.

Other Important Activities


Following are some of the important activities that an Operating System performs −

 Security − By means of password and similar other techniques, it prevents unauthorized


access to programs and data.

 Control over system performance − Recording delays between request for a service
and response from the system.

 Job accounting − Keeping track of time and resources used by various jobs and users.

 Error detecting aids − Production of dumps, traces, error messages, and other
debugging and error detecting aids.

 Coordination between other softwares and users − Coordination and assignment of


compilers, interpreters, assemblers and other software to the various users of the
computer systems.
Disk partitioning means, divide a single hard drive into many logical drives using partition
editors such as fdisk, parted tools. Once a disk is divided into several partitions, directories and
files of different categories may be stored in different partitions.

Many new Linux admins create only two partitions / (root) and swap for entire hard drive. so all
other directories of linux like /usr, /var, /bin will be created under this /(root). Later on there may
be a need to create new partition for these directories or for other mount points, So admins
should be able to create a new partition manually using partition editors.

In Linux, partitions are represented by device files. These devices files are located in /dev. Some
example files listed below.
[root@node1 ~]# ll /dev/
Have a look on the first integer of two lines from the output, those starts with "b" for first two
line which are block devices (hda and sda). In Linux, all disks are represented as block devices
only.

How to Create and Delete Partitions using fdisk in Linux.

brw-rw---- 1 root disk 3, 0 May 5 1998 hda


brw-rw---- 1 root disk 8, 0 May 5 1998 sda
crw------- 1 root tty 4, 64 May 5 1998 ttyS0
as block devices only.

Linux maintains the naming conventions for IDE drives and SCSI Disks. SCSI drives follow a
similar pattern; They are represented by 'sd' instead of 'hd'.

Once a drive has been partitioned, the partitions will be represented as numbers on
the end of the names.

For example, lets assume that we have two IDE Drives with partitions as below.

This is all we have to know to deal with linux disk devices file.

1. Primary Partitions - The number of partitions was limited from the very beginning
and we can have only four partitions. These partitions are now called primary
partitions.

2. Extended Partitions - The extended partitions is a way to overcome the limitation of


four primary partitions on a drive. If you want to have more than four partitions, You
can put lots of Partitions inside it.

3. Logical Partitions - A logical partition is a a partition that has been created inside
of an extended partition.
In linux, A partition is labeled to host a certain kind of file system.
Naming Conventions
1. IDE drives device names would be /dev/hda, /dev/hdb.
/dev/hda - "a" refers, its a first drive.
/dev/hdb - "b" refers, its a second drive.
/dev/hdc - "c" refers, its a third drive.
/dev/hdd - "d" refers, its a fourth drive.
2. SCSI Drives device names would be /dev/sda, /dev/sdb.
/dev/sda - "a" refers, its a first drive.
/dev/sdb - "b" refers, its a second drive.
/dev/hda1 - First partition of first drive.
/dev/hda2 - Second partition of first drive.
/dev/hdb1 - First partition of second drive.
/dev/hdb2 - Second partition of second drive.
Partition Types
In linux, A partition is labeled to host a certain kind of file system. A filesystem is the methods
and data structures that an operating system uses to keep track of files on a disk or partition; that
is, the way the files are organized on the disk. The word is also used to refer to a partition or disk
that is used to store the files or the type of the filesystem.

Such a file system could be the linux standard ext3 file system, ext4 filesystem, linux swap
partitions or other filesystems. There is a numerical code associated with each things. For
example, the code for linux filesystem is 0x83 and linux swap is 0x82. Run "/sbin/sfdisk -T" to
see a list of partition types and their codes, execute /sbin/sfdisk

A filesystem is the methods and data structures that an operating system uses to keep track of
files on a disk or partition; that is, the way the files are organized on the disk. The word is also
used to refer to a partition or disk that is used to store the files or the type of the filesystem.

Such a file system could be the linux standard ext3 file system, ext4 filesystem, linux swap
partitions or other filesystems. There is a numerical code associated with each things. For
example, the code for linux filesystem is 0x83 and linux swap is 0x82.
Run
"/sbin/sfdisk -T" to see a list of partition types and their codes, execute /sbin/sfdisk –T

Swap space and its management

A swap space is an area of a disk which can be used with the Linux kernel memory management
subsystem. Swap spaces are used to supplement the system RAM by holding inactive pages of
memory. The combined system RAM plus swap space is called virtual memory. When the
memory usage in a system exceeds a defined limit, the kernel will comb through RAM looking
for idle memory pages assigned to processes.

The kernel will write the idle page to the swap area, and will reassign the RAM page to be used
by another process. If a program requires access to page that has been written to disk, the kernel
will locate another idle page of memory, write it to disk, then recall the needed page from the
swap area. Since swap areas reside on a disk, swap is incredibly slow compared to RAM. While
it is used to augment system RAM, usage of swap spaces should be kept to a minimum whenever
possible.

Create a swap space


To create a swap space, an administrator need to do three things:
1) Create a partition
2) Set the type of the partition as 82 Linux swap
3) Format a swap signature on the device.
Use a tool, such as fdisk, to create a partition of the desired size.
$ fdisk /dev/vdb

Assign the partition type

After the swap partition, has been created, it is recommended to change the partition’s type, or
system ID, to 82 Linux swap. The partition type is not used by utilities any longer, having the
type set allows administrators to quickly determine the partitions purpose

Format the device


The mkswap command applies a swap signature to the device. Unlike other formatting utilities,
mkswap writes a single block of data at the beginning of the device, leaving the rest of the device
unformatted so it can be used for storing memory pages.
$ mkswap /dev/vdb1

Activate a swap space


An administrator can use the swapon command to activate a formatted swap space. Swapon can
be called on the device, or swapon -a will activate all swap spaces listed in the /etc/fstab file.
$ free
total used free shared buffers cached
Mem: 595 482 112 0 63 324
-/+ buffers/cache: 93 501

$ swapon /dev/vdb1
$ free
total used free shared buffers cachedMem: 595 482 112 0
63 324-/+ buffers/cache: 93 501
Swap: 240 0 240

Persistently activate swap space


It is likely that a swap space will be required to automatically activate every time the machine
boots. In order for the machine to activate the swap space at every boot, it must be configured in
the /etc/fstab file. If needed an administrator can deactivate a swap space using the swapoff
command.

A swapoff will only be successful if any swapped data can be written to other active swap
spaces or back into memory. If data cannot be written to other places, the swapoff will fail, with
an error, and the swap space will stay active.
The following is an example line in /etc/fstab adding a previously created swap space.
UUID=fdb7fa60-b781-44a8-961b-37ac3ef572bf swap swap defaults 0 0

The example uses the UUID as the first field. The UUID is stored in the swap signature stored on
the device, and was part of the output of mkswap. If the output of mkswap has been lost, the
blkid command can be used to scan the system and report on all attached block devices. The raw
device name can also be used in the first field.

The second field is typically reserved for the mount point. However, for swap devices, which are
not accessible through the directory structure, this field is the placeholder value swap.

The third filed is the file system type. The file system type for a swap space is swap.

The fourth field is for options. In the example, the option defaults is used. Defaults includes the
mount option auto, which is what causes the swap space to be automatically activated at boot.

The final two fields are the dump flag and fsck order. Swap spaces require neither backing up
nor file system checking.

File system and Directory Structures in Linux

A file system is a logical collection of files on a partition or disk. A partition is a container for
information and can span an entire hard drive if desired.

Your hard drive can have various partitions which usually contain only one file system, such as
one file system housing the /file system or another containing the /home file system.

One file system per partition allows for the logical maintenance and management of differing
file systems.

Everything in Unix is considered to be a file, including physical devices such as DVD-ROMs,


USB devices, and floppy drives.

Directory Structure
Unix uses a hierarchical file system structure, much like an upside-down tree, with root (/) at the
base of the file system and all other directories spreading from there.

A Unix filesystem is a collection of files and directories that has the following properties −

 It has a root directory (/) that contains other files and directories.

 Each file or directory is uniquely identified by its name, the directory in which it resides,
and a unique identifier, typically called an inode.
 By convention, the root directory has an inode number of2 and the lost+found directory
has an inode number of3. Inode numbers 0 and 1 are not used. File inode numbers can
be seen by specifying the -i option to ls command.

 It is self-contained. There are no dependencies between one filesystem and another.

The directories have specific purposes and generally hold the same types of information for
easily locating files. Following are the directories that exist on the major versions of Unix −

Sr.No. Directory & Description

1 /

This is the root directory which should contain only the


directories needed at the top level of the file structure

2 /bin

This is where the executable files are located. These files are
available to all users

3 /dev

These are device drivers

4 /etc

Supervisor directory commands, configuration files, disk


configuration files, valid user lists, groups, ethernet, hosts, where
to send critical messages

5 /lib

Contains shared library files and sometimes other kernel-related


files

6 /boot

Contains files for booting the system


7 /home

Contains the home directory for users and other accounts

8 /mnt

Used to mount other temporary file systems, such


ascdrom and floppy for the CD-ROM drive and floppy
diskette drive, respectively

9 /proc

Contains all processes marked as a file by process number or


other information that is dynamic to the system

10 /tmp

Holds temporary files used between system boots

11 /usr

Used for miscellaneous purposes, and can be used by many


users. Includes administrative commands, shared files, library
files, and others

12 /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

13 /sbin

Contains binary (executable) files, usually for system


administration. For example, fdisk and ifconfig utlities

14 /kernel
Contains kernel files

Navigating the File System


Now that you understand the basics of the file system, you can begin navigating to the files you
need. The following commands are used to navigate the system −

Sr.No. Command & Description

1 cat filename

Displays a filename

2 cd dirname

Moves you to the identified directory

3 cp file1 file2

Copies one file/directory to the specified location

4 file filename

Identifies the file type (binary, text, etc)

5 find filename dir

Finds a file/directory

6 head filename

Shows the beginning of a file

7 less filename

Browses through a file from the end or the beginning

8 ls dirname
Shows the contents of the directory specified

9 mkdir dirname

Creates the specified directory

10 more filename

Browses through a file from the beginning to the end

11 mv file1 file2

Moves the location of, or renames a file/directory

12 pwd

Shows the current directory the user is in

13 rm filename

Removes a file

14 rmdir dirname

Removes a directory

15 tail filename

Shows the end of a file

16 touch filename

Creates a blank file or modifies an existing file or its attributes

17 whereis filename

Shows the location of a file

18 which filename
Shows the location of a file if it is in your PATH

Filesystem in Linux

In a computer the hard disk forms a physical medium which can store files, and thus forms a
filesystem. The major filesystem types in Linux are

1) EXT3

2) EXT4

3) VFAT

4) Swap

Ext3 and Ext4 stands for extended file system. VFAT is a filesystem equivalent to the windows
FAT ( File Allocation Table ) file system, it stands for Virtual FAT.

Ext3 and Ext4 are used to create and access logical volume. VFAT is used in external medias
like Pendrive and all.

Swap is used to create a swap area in the hard disk, which can be used as a virtual memory. The
total memory which a running application can see is the sum of physical memory ( RAM ) and
the Virtual memory ( Swap ).

Mount points in Linux

The windows use a method called “Drive letter mounting” to access the disc space. Windows
users are familiar with the terms C-drive, D-drive etc. But Linux use an entirely different
technique called “mount point”.

Unlike windows we can see the mounted disk space as folders under the root of the file system.
In windows we can see them as drives.

Examples of mount points are /, /boot, /home etc.


Filesystem hierarchy in Linux

In Linux the file system is maintained in a hierachial method. The “/” forms the root of all
filesystem, under which all other directories are mounted.

Filesystem hierarchy in Linux

Mount points and their Usage

Directory Usage

/bin Binary directory; Stores commands used in Linux


/boot Store files like boot loader, required during boot time

/dev Device information directory. Device files are kept here

/etc System configuration files are stored here

/home Document directory of all normal users

/root Document directory of super-user

/mnt Mount directory for manual mounting

/media Auto-mount directory

/lib Shared libraries and kernel modules are stored here

/lost + found Back-up point for ext3 file system

/proc Process information directory. It provides interface to kernel data structures

/tmp Directory provided for storing temporary files

/sbin Directory for storing only default system commands

/var Varying file directory for storing regularly updating files

/opt Optional directory for installing additional software

In practical cases, there could be more mount points than give in the above list

User types in linux

Linux has three types of users

1) Super-user

2) Normal-user

3) System user
Super-user in Linux is called “root”. Root user has complete previlage in Linux. Only he has the
administratory power.

Normal user doesn't have administrator power. Normal users have only a limited access. It is the
root user which creates the normal user. In certain Linux OS there is no root user, like in
Ubuntu, Linuxmint etc. In such cases we can use commands to give normal user an
administrative privilage.

System users are the users created by applications in the system. For example in servers the
application allows only authorised users to access its service.

Switching user interface in linux

Linux will boot into a default user interface, which is the GUI. We can then switch to TUI and
also switch back from TUI to GUI.

Multi-Processing
A multiprocessing system consists of a number of processors communicating via a bus or a
network. There are two types of multiprocessing systems: loosely coupled and tightly coupled.

Loosely coupled systems consist of processors that operate stand-alone.Each processor has its
own bus, memory, and I/O subsystem, and communicates with other processors through the
network medium. Loosely coupled systems can be either homogeneous or heterogeneous.

Tightly coupled systems consist of processors that share the memory, bus, devices, and
sometimes cache. Tightly coupled systems run a single instance of the operating system. Tightly
coupled systems can be classified into symmetric and asymmetric systems.

Asymmetric systems are configured so that each processor is assigned a specific task.
Asymmetric systems have a single "master" processor that controls all others. Symmetric
systems treat all processors the same way—processes have equal access to all system resources.
In the symmetric model, all tasks are spread equally across all processors.

Symmetric systems are subdivided into further classes consisting of dedicated and shared cache
systems. Symmetrical Multiprocessing (SMP) systems have become very popular and have
become the default choice for many large servers.
Concurrency and Data Serialization

In an ideal world, an SMP system with n processors would perform n times better than a
uniprocessor system. In reality, this is not the case. The main reason that no SMP system is
100% scalable is because of the overhead involved in maintaining additional processors.

Locks, Lock Granularity, and Locking Overhead

Locks basically protect multiple threads from accessing or modifying a piece of critical
information at the same time. Locks are especially used on SMP systems where multiple
processors execute multiple threads at the same time.

The problem with locking is that if two or more processors are competing for the same lock at
the same time, only one is granted the lock, and the other waits, spinning, for the lock to be
released. In other words, the other processors are not really doing any useful work. Locking,
therefore, must be limited to the smallest amount of time possible.

Another common technique used to address this problem is to employ finer-grain locking. With
finer-grain locking, instead of using a single lock to protect 100 things, 100 locks are used
instead. Although the concept seems very simple, most of the time, it is hard to implement
because of various interactions, dependencies, and deadlock. You need to program methodically
to prevent deadlock situations, compared to having a single lock.

Another important area to consider is locking overhead. All locking techniques come with a
price. Operating system designers need to choose the right kind of locking primitive to address a
rights issue. In Linux 2.6, most global locks are removed and most of the locking primitives are
optimized for extremely low overhead.

Cache Coherency

Cache coherency is a problem that occurs in multiprocessors, because each processor has an
individual cache, and multiple copies of certain data exist in the system. When the data is
changed, only one processor’s cache has the new value. All other processors’ cache has old
values.

Processor Affinity

Processor affinity is one of the most important things that can improve system performance. As
processes access various resources in the system, lots of information about the resources will be
in processor caches, so it’s better for a processor to run on the same processor due to the cache
warmth.

In some architectures, especially with NUMA, some resources are closer to the processor
compared to others in the same system. In these systems, processor affinity is extremely
important for system performance.
Load Sharing and Multi Threading in Linux

A thread is a flow of execution through the process code, with its own program counter that
keeps track of which instruction to execute next, system registers which hold its current working
variables, and a stack which contains the execution history.

A thread shares with its peer threads few information like code segment, data segment and open
files. When one thread alters a code segment memory item, all other threads see that.
A thread is also called a lightweight process. Threads provide a way to improve application
performance through parallelism. Threads represent a software approach to improving
performance of operating system by reducing the overhead thread is equivalent to a classical
process.

Each thread belongs to exactly one process and no thread can exist outside a process. Each
thread represents a separate flow of control. Threads have been successfully used in
implementing network servers and web server. They also provide a suitable foundation for
parallel execution of applications on shared memory multiprocessors. The following figure
shows the working of a single-threaded and a multithreaded process.

Difference between Process and Thread


S.N. Process Thread
Process is heavy weight or resource Thread is light weight, taking lesser resources
1
intensive. than a process.
2 Process switching needs interaction with Thread switching does not need to interact with
operating system. operating system.
In multiple processing environments, each
All threads can share same set of open files,
3 process executes the same code but has its
child processes.
own memory and file resources.
If one process is blocked, then no other
While one thread is blocked and waiting, a
4 process can execute until the first process
second thread in the same task can run.
is unblocked.
Multiple processes without using threads Multiple threaded processes use fewer
5
use more resources. resources.
In multiple processes each process One thread can read, write or change another
6
operates independently of the others. thread's data.
Advantages of Thread
 Threads minimize the context switching time.
 Use of threads provides concurrency within a process.
 Efficient communication.
 It is more economical to create and context switch threads.
 Threads allow utilization of multiprocessor architectures to a greater scale and efficiency.
Types of Thread
Threads are implemented in following two ways −
 User Level Threads − User managed threads.
 Kernel Level Threads − Operating System managed threads acting on kernel, an
operating system core.
User Level Threads
In this case, the thread management kernel is not aware of the existence of threads. The thread
library contains code for creating and destroying threads, for passing message and data between
threads, for scheduling thread execution and for saving and restoring thread contexts. The
application starts with a single thread.
Advantages
 Thread switching does not require Kernel mode privileges.
 User level thread can run on any operating system.
 Scheduling can be application specific in the user level thread.
 User level threads are fast to create and manage.
Disadvantages
 In a typical operating system, most system calls are blocking.
 Multithreaded application cannot take advantage of multiprocessing.
Kernel Level Threads
In this case, thread management is done by the Kernel. There is no thread management code in
the application area. Kernel threads are supported directly by the operating system. Any
application can be programmed to be multithreaded. All of the threads within an application are
supported within a single process.
The Kernel maintains context information for the process as a whole and for individuals threads
within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs
thread creation, scheduling and management in Kernel space. Kernel threads are generally
slower to create and manage than the user threads.
Advantages
 Kernel can simultaneously schedule multiple threads from the same process on multiple
processes.
 If one thread in a process is blocked, the Kernel can schedule another thread of the same
process.
 Kernel routines themselves can be multithreaded.
Disadvantages
 Kernel threads are generally slower to create and manage than the user threads.
 Transfer of control from one thread to another within the same process requires a mode
switch to the Kernel.
Multithreading Models
Some operating system provide a combined user level thread and Kernel level thread facility.
Solaris is a good example of this combined approach. In a combined system, multiple threads
within the same application can run in parallel on multiple processors and a blocking system call
need not block the entire process. Multithreading models are three types
 Many to many relationship.
 Many to one relationship.
 One to one relationship.
Many to Many Model
The many-to-many model multiplexes any number of user threads onto an equal or smaller
number of kernel threads.
The following diagram shows the many-to-many threading model where 6 user level threads are
multiplexing with 6 kernel level threads. In this model, developers can create as many user
threads as necessary and the corresponding Kernel threads can run in parallel on a multiprocessor
machine. This model provides the best accuracy on concurrency and when a thread performs a
blocking system call, the kernel can schedule another thread for execution.

Many to One Model


Many-to-one model maps many user level threads to one Kernel-level thread. Thread
management is done in user space by the thread library. When thread makes a blocking system
call, the entire process will be blocked. Only one thread can access the Kernel at a time, so
multiple threads are unable to run in parallel on multiprocessors.
If the user-level thread libraries are implemented in the operating system in such a way that the
system does not support them, then the Kernel threads use the many-to-one relationship modes.

One to One Model


There is one-to-one relationship of user-level thread to the kernel-level thread. This model
provides more concurrency than the many-to-one model. It also allows another thread to run
when a thread makes a blocking system call. It supports multiple threads to execute in parallel on
microprocessors.
Disadvantage of this model is that creating user thread requires the corresponding Kernel thread.
OS/2, windows NT and windows 2000 use one to one relationship model.
Difference between User-Level & Kernel-Level Thread
S.N. User-Level Threads Kernel-Level Thread
User-level threads are faster to create and Kernel-level threads are slower to create and
1
manage. manage.
Implementation is by a thread library at the Operating system supports creation of Kernel
2
user level. threads.
User-level thread is generic and can run on Kernel-level thread is specific to the
3
any operating system. operating system.
Multi-threaded applications cannot take Kernel routines themselves can be
4
advantage of multiprocessing. multithreaded.

Types of users in Linux

Linux user
A user or account of a system is uniquely identified by a numerical number called the
UID (unique identification number). There are two types of users – the root or super user and
normal users. A root or super user can access all the files, while the normal user has limited
access to files. A super user can add, delete and modify a user account.
The full account information is stored in the /etc/passwd file and a hash password is stored in the
file /etc/shadow.

Creating a user with a default setting: A user can be added by running theuseradd command at
the command prompt. After creating the user, set a password using the
passwd utility, as follows:

[root@localhost bhargab]# useradd anirban


[root@localhost bhargab]# passwd anirban
Changing password for user anirban.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

The system automatically assigns a UID, creates the home directory (/home/<username>) and
sets the default shell to /bin/bash. The useradd command creates a user private group whenever a
new user is added to the system and names the group after the user.

Specifying a user’s full name when creating a user: A systems administrator can use the –c
option with useradd to specify the user’s full name, as shown below:

[root@localhost bhargab]# useradd -c “Anirban Choudhury” anirban

Creating a user with the UID: You can create a user with a custom UID with the –uoption, as
follows:

[root@localhost bhargab]# useradd -u 1036 anirban

Creating a user with non-default home directory: A non-default home directory can be set by
executing the following command:
[root@localhost bhargab]# useradd –d /home/test anirban

Adding a user to a primary group and supplementary group: A systems administrator can
specify a primary group and a supplementary one by specifying the–g and –G option,
respectively.

[root@localhost bhargab]# useradd -g “head” -G “faculty” anirban

Locking and unlocking a user: A super user can lock and unlock a user account. To lock an
account, one needs to invoke passwd with the -l option.

[root@localhost bhargab]# passwd -l anirban


Locking password for user anirban.
passwd: Success
The –u option with passwd unlock an account, as
shown below:

[root@localhost bhargab]# passwd -u anirban


Unlocking password for user anirban.
passwd: Success
Changing a user name: The –l option with the usermod command changes the login (user)
name, as shown below:

[root@localhost bhargab]# usermod -l “nishant” anirban


Removing a user: Combining userdel with the –r option drop a user and the home directory
associated with that user, as shown below:

[root@localhost bhargab]# userdel -r nishant


Linux group
Linux group is a mechanism to organise a collection of users. Like the user ID, each
group is also associated with a unique ID called the GID (group ID). There are two types of
groups – a primary group and a supplementary group.
Each user is a member of a primary group and of zero or ‘more than zero’ supplementary groups.
The group information is stored in /etc/group and the respective passwords are stored in
he /etc/gshadow file. Some operations such as creating, deleting and modifying on a group are
discussed below.

Creating a group with default settings: To add a new group with default settings, run
the groupadd command as a root user, as shown below:

[root@localhost bhargab]# groupadd employee


If you wish to add a password, then type gpasswd with the group name, as follow:

[root@localhost bhargab]# gpasswd employee


Changing the password for group employee
New Password:
Re-enter new password:

Creating a group with a specified GID: To explicitly specify the GID of a group, execute
the groupadd command with the –g option, as follow:

[root@localhost bhargab]# groupadd -g 1200 manager

Removing group password: To remove a group password, run gpasswd –r with the relevant
group name, as follow:

[root@localhost bhargab]# gpasswd -r employee

Changing the group’s name: To change the group’s name, run the groupmodcommand with
the -n option as a super user, as shown below:

[root@localhost bhargab]# groupmod -n hrmanager employee


Changing the group’s GID: To change the GID of a group, run the groupmodcommand with –
g, as follow:

[root@localhost bhargab]# groupmod -g 1050 manager

Deleting a group: Before deleting a primary group, delete the users of that primary group. To
delete a group, run the groupdel command with the group name, as shown below:

[root@localhost bhargab]# groupdel employee

Capabilities of Super Users and Equivalents

The “root” super user is the king of users in Linux/Unix. Having root access grants full and
unlimited access to the Linux box. I will show you how to allow root access to a user in a Linux
system. Typically, root level access is used in system administration. So it is always a pain to give
root access to other users. You need to be careful and should withdraw the access once the need to
do so is over.

According to Linux file system permissions, root or super user has full permission to read(r), write
(w) and execute(x) any file. By default root user id is '0'.

To create two users namely user1 and user2. Then I will show you how to give root access to
user1 .

Method 1: Adding to Root Group using usermod

Let see how we can grant normal user root access by adding to root group.

[root@mypc Desktop]# adduser user1


[root@mypc Desktop]# adduser user2
[root@mypc Desktop]# groupadd test
These are the groups I have in my Linux box.

[root@mypc /]# groups


root bin daemon sys adm disk wheel
To add user1 to root group as follows:
[root@mypc Desktop]# usermod -G root user1
The command given below provides the existing user with the root privilege

[root@mypc Desktop]# usermod -g 0 -o root_user

Method 2: Adding to Root Group using Useradd Command

I have added a new user, 'user3' to the root group using one single command:

[root@mypc/]#useradd-m-Grootuser3
[root@mypc/]#groupsuser3
user3 : user3 root
Another option using useradd command

Useradd -c “Imitation Root” -d /home/root_user -m -k /etc/skel -s /bin/bash -u 0 -o -g root


root_user

Method 3: Editing /etc/passwd file

Edit /etc/passwd for the particular user. Change the user's UID and GID to '0'. This will give root
permissions to user.

root:x:0:0:root:/root:/bin/bash
temproot:x:128:128:temproot
Now, temproot user should have root privilege:

root:x:0:0:root:/root:/bin/bash
temproot:x:0:0:temproot
Note: This is not the recommended method for granting root access

Method 4: Setting as Sudo User

The sudo configuration file is /etc/sudoers and you can edit this file using visudo command: #
visudo.

Using visudo protects from conflicts and guarantees that the right syntax is used.
To give full access to specific users

Add the entry given below in the file:

bob, tom ALL=(ALL) ALL


Following this method is not a good idea because this allows both bob and tom to use the su
command to grant themselves permanent root privileges. Thereby skipping the command logging
features of sudo.

Granting access to specific files to one particular user

This entry allows bob and all the other members of the group operator to gain access to all the
program files in the /sbin and /usr/sbin directories, as well as the privilege of running the command
/usr/oracle/backup.pl.

bob, %operator ALL= /sbin/, /usr/sbin, /usr/oracle/backup.pl

You might also like