MSIT 3A

203
INFORMATION TECHNOLOGY PROGRAMMES Bachelor of Science in Information Technology - B.Sc. (IT) Master of Science in Information Technology - M.Sc. (IT) In collaboration with KUVEMPU UNIVERSITY M.Sc.(IT) - 3 rd Semester MSIT - 3A Linux Internals Directorate of Distrance Education Kuvempu University Shankaraghatta, Shimoga District, Karnataka Universal Education Trust Bangalore PDF created with pdfFactory Pro trial version www.pdffactory.com

Transcript of MSIT 3A

Page 1: MSIT 3A

INFORMATION TECHNOLOGY PROGRAMMESBachelor of Science in Information Technology - B.Sc. (IT)Master of Science in Information Technology - M.Sc. (IT)

Incollaboration

with

KUVEMPU UNIVERSITY

M.Sc.(IT) - 3rd Semester

MSIT - 3A Linux Internals

Directorate of Distrance EducationKuvempu University

Shankaraghatta, Shimoga District, Karnataka

Universal Education TrustBangalore

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 2: MSIT 3A

Titles in this Volume :MSIT - 3A Linux Internals

Prepared by UNIVERSAL EDUCATION TRUST (UET)Bangalore

First Edition : May 2005

Copyright © by UNIVERSAL EDUCATION TRUST, BangaloreAll rights reserved

No Part of this Book may be reproducedin any form or by any means without the writtenpermission from Universal Education Trust, Bangalore.

All Product names and company names mentionedherein are the property of their respective owners.

NOT FOR SALEFor personal use of Kuvempu UniversityIT - Programme Students only.

Corrections & Suggestionsfor Improvement of Study materialare invited by Universal Education Trust, Bangalore.

E-mail : [email protected]

Printed at :Mayur Print AdsBangalore - 20Ph : 94480 - 42724

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 3: MSIT 3A

LINUX INTERNALS(MSIT - 3A)

: Contributing Authors :

Sri. M.V. Panduranga RaoResearch Scholar,

National Institute of Technology, KarnatakaFormerly KREC, Suratkal, Mangalore.

Lecturer, Dept. of Information Science & Engg.JNNCE, Shimoga - 577204.

&

Smt. K. RoopaLecturer, Dept. of C.Sc. & Engg.

JNNCE, Shimoga - 577204

Under the guidance of

Smt. K. Roopa Dr. K. Chandrashekar ShetProfessor

Department of Computer EngineeringNational Institute of Technology, Karnataka

Surathkal, Mangalore, INDIAP.O. Srinivasnagar - 575025

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 4: MSIT 3A

MSIT 3A Linux Internals V

Contents

Chapter 1

INTRODUCTION 1

1.0 Introduction and Objectives........................................................ 11.1 Unix and Linux: Features ......................................................... 21.2 Unix System Architecture ........................................................ 31.3 Unix Philosophy ...................................................................... 41.4 What is Linux? ........................................................................ 41.5 Using a Linux System: Login .................................................... 51.6 Linux Command Line .............................................................. 51.7 Logging Out ........................................................................... 61.8 Command Syntax .................................................................... 61.9 Files ...................................................................................... 61.10 Linux Directories...................................................................... 71.11 File System Organization............................................................ 71.12 Creating Files with cat............................................................... 101.13 Displaying Files’ Contents with cat.............................................. 101.14 Deleting Files with rm .............................................................. 111.15 Unix Command Feedback .......................................................... 111.16 Copying and Renaming Files with cp and mv .............................. 111.17 Filename Completion ................................................................. 121.18 Command History .................................................................... 121.19 Summary.................................................................................. 121.20 Check Your Progress................................................................. 13

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 5: MSIT 3A

VI Chapter 1 - Introduction

Chapter 2

LINUX COMMANDS 18

2.0 Introduction and objectives ........................................................ 182.1 Basic Linux Commands............................................................. 192.2 Help commands........................................................................ 212.3 General commands.................................................................... 222.4 File management commands...................................................... 242.5 Finding files.............................................................................. 272.6 Linux Files and File Permission................................................... 272.7 File names and permission characters.......................................... 282.8 Examples on files...................................................................... 282.9 Setting Keystrokes.................................................................... 302.10 Keys and terminal configuration ................................................. 302.11 Summary.................................................................................. 312.12 Check Your Progress................................................................. 31

Chapter 3

PROCESSES 37

3.0 Introduction and objectives......................................................... 373.1 Looking at Processes................................................................. 383.2 Process IDs............................................................................. 383.3 Viewing Active Processes.......................................................... 393.4 ps Output Formats..................................................................... 393.5 Killing a Process....................................................................... 413.6 Creating Processes................................................................... 423.7 Creating Using system()............................................................ 423.8 Creating Using system calls – fork, exec..................................... 433.9 Creating by Calling fork............................................................. 433.10 Creating by Using the exec Family.............................................. 443.11 Creating by Using fork and exec Together................................... 453.12 Process Scheduling.................................................................... 453.13 Signals..................................................................................... 463.14 Some Linux daemons................................................................. 473.15 popular daemons....................................................................... 483.16 Zombie Proces.......................................................................... 503.17 Threads.................................................................................... 51

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 6: MSIT 3A

MSIT 3A Linux Internals VII

3.18 Processes Vs. Threads.............................................................. 523.19 Summary.................................................................................. 533.20 Check Your Progress................................................................. 54

Chapter 4

SHELL PROGRAMMING 60

4.0 Introduction and Objectives........................................................ 604.1 Creating a shell script................................................................ 614.2 Meta characters........................................................................ 624.3 Positional Parameters and Shell Variables.................................... 634.4 Built-in shell commands and variables.......................................... 644.5 Iteration, control and if statements.............................................. 664.6 Shell operators ........................................................................ 684.7 The test Command.................................................................... 694.8 An example script..................................................................... 714.9 Environment Variables .............................................................. 724.10 Summary.................................................................................. 734.11 Check Your Progress................................................................. 74

Chapter 5

FILE SYSTEM 79

5.0 Introduction and Objectives ....................................................... 795.1 Filesystem Overview ................................................................ 805.2 Types of Files........................................................................... 805.3 Directory pointer....................................................................... 835.4 Directory Hierarchy ................................................................. 835.5 Pathnames .............................................................................. 845.6 Current Directory ..................................................................... 855.7 Dot (.) and DotDot(..) .............................................................. 855.8 Moving and Copying Files ......................................................... 865.9 Removing Files ........................................................................ 865.10 Operations on Directories ......................................................... 875.11 Inodes .................................................................................... 875.12 Options of Inodes ................................................................... 885.13 Links ...................................................................................... 885.14 Hard links ............................................................................... 89

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 7: MSIT 3A

5.15 Soft links ................................................................................. 895.16 Access Control and UID .......................................................... 905.17 Categories of Access Control .................................................... 915.18 Access Control – Example ........................................................ 915.19 Changing Access Previleges: hmod............................................ 915.20 chmod symbolically .................................................................. 925.21 chmod numerically ................................................................... 925.22 umask Masking Privileges ......................................................... 925.23 Filesystem Structure ................................................................. 935.24 /etc/fstab - Example ................................................................ 935.25 Special Files - /dev ................................................................ 935.26 Special Files - /proc ............................................................... 945.27 Mounting Additional Volumes .................................................... 945.28 Mounting shared filesystems ..................................................... 955.29 Summary ................................................................................ 955.30 Check Your Progress................................................................ 96

Chapter 6

FILE SYSTEM ADMINISTRATION 102

6.0 Introduction and objectives ........................................................ 1026.1 Inode in depth ......................................................................... 1036.2 Inode table entry ...................................................................... 1036.3 Links: relationship with inode ..................................................... 1046.4 Hard links ............................................................................... 1056.5 Soft links ................................................................................. 1056.6 Non-native filesystems ............................................................ 1066.7 Disk checking and recovery (fsck) ............................................. 1066.8 Check a Linux ext2 filesystem (e2fsck)....................................... 1076.9 Disk free space (df).................................................................. 1076.10 Disk usage (du)......................................................................... 1086.11 Disk partitioning concepts .......................................................... 1086.12 A Partitioned Disk ................................................................... 1096.13 Making and changing partitions .................................................. 1096.14 How many partitions? ............................................................... 1106.15 What size partitions? ................................................................. 1106.16 BIOS problems with LILO and partitions .................................... 1106.17 Disk partitioning tools ................................................................ 111

VIII Chapter 1 - Introduction

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 8: MSIT 3A

6.18 Using fdisk()............................................................................. 1116.19 The fdisk interface ................................................................... 1126.20 Interactive commands in fdisk..................................................... 1126.21 Making Linux filesystems (mke2fs) ............................................ 1136.22 Block devices ........................................................................... 1136.23 Character devices ..................................................................... 1146.24 Summary ................................................................................. 1146.25 Check Your Progress................................................................. 115

Chapter 7

SYSTEM ADMINISTRATION 123

7.0 Introduction and objectives......................................................... 1237.1 The superuser account............................................................... 1247.2 User accounts /etc/passwd......................................................... 1247.3 Groups..................................................................................... 1257.4 Managing Linux users................................................................ 1277.5 User reference files................................................................... 1287.6 User modifications.................................................................... 1287.7 Examples of making changes to permissions................................ 1297.8 Some administration commands.................................................. 1307.9 Summary.................................................................................. 1327.10 Check Your Progress................................................................. 132

Chapter 8

EDITORS AND TOOLS 135

8.0 Introduction and objectives......................................................... 1358.1 Linux VI editor......................................................................... 1368.2 The emacs editor...................................................................... 1388.3 System and network configuration............................................... 1408.4 X Configuration........................................................................ 1408.5 Library and kernel dependency management................................ 1418.6 General Diagnostic.................................................................... 1418.7 To remotely use Xwindows from Ms Windows............................. 1428.8 Network application commands.................................................. 1438.9 Summary.................................................................................. 1448.10 Check Your Progress................................................................. 145

MSIT 3A Linux Internals IX

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 9: MSIT 3A

Chapter 9

ISTALLATION OF LINUX 148

9.0 Introduction and objectives......................................................... 1489.1 Devices of installation................................................................ 1499.2 Partitioning hard disk................................................................. 1509.3 Partition sizes........................................................................... 1509.4 Mount points............................................................................. 1519.5 Mounting partitions at startup..................................................... 1519.6 The fstab file............................................................................ 1529.7 Know your hardware................................................................. 1539.8 Creating the Linux boot disk....................................................... 1549.9 Making a diskette under MS-DOS............................................... 1549.10 Making a diskette under a Linux-Like OS..................................... 1559.11 Beginning the installation of Linux .............................................. 1559.12 Installation options - class and method ........................................ 1569.13 Manual configurations................................................................ 1569.14 Package installations.................................................................. 1589.15 Standard linux partition filesystem types....................................... 1599.16 Network administration tools....................................................... 1629.17 Summary.................................................................................. 1649.18 Check Your Progress................................................................. 164

Chapter 10

GLOSSARY 169

X Chapter 1 - Introduction

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 10: MSIT 3A

Chapter 1

Introduction

1.0 INTRODUCTION AND OBJECTIVES

Linux is an operating system that was first created at the University of Helsinki in Finland by ayoung student named Linus Torvalds. At this time the student was working on a UNIX systemthat was running on an expensive platform. Because of his low budget, and his need to work at

home, he decided to create a copy of the UNIX system in order to run it on a less expensive platform,such as an IBM PC. He began his work in 1991 when he released version 0.02 and worked steadily until1994 when version 1.0 of the Linux Kernel was released.

There are no royalty or licensing fees for using Linux, and the source code can be modified to fit yourneeds. Because it comes with source code to the kernel, it is quite portable. Linux runs on more CPUsand platforms than any other computer operating system.

Linux is a true multi-tasking operating system similar to it’s brother, UNIX. It uses sophisticated, state-of-the-art memory management to control all system processes. That means that if a program crashesyou can kill it and continue working with confidence. Another benefit is that Linux is practically immunizedagainst all kinds of viruses that we find in other operating systems.

ObjectivesAt the end of this unit, You would be able to

ð know important features of Linux

ð Unix system Architecture

ð Significance of using a Linux System

Chapter 1 - Introduction 11

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 11: MSIT 3A

Chapter 1 - Introduction12

ð Linux command Line

ð Exhibit login, logoff, Issue basic commands & switching to another account

ð Linux directories and file system organization

ð Know commands related to file retrievals

1.1 Unix and Linux: featuresØ Linux is based on Unix.

♦ Unix philosophy.♦ Unix commands.♦ Unix standards and conventions.

Ø There is some variation between Unix operating systems.

♦ Especially regarding system administration.♦ Often Linux-specific things in these areas.

Important features of Linux

Ø Full multitasking and 32-bit support. Linux, like all other versions of UNIX, is a real multitaskingsystem, allowing multiple users to run many programs on the same system at once. Linux isalso a full 32-bit operating system, utilizing the special protected-mode features of Intel80386 and later processors and their work-alikes. Linux inherited all the features of UNIXoperating system, henceforth we have used the name Linux or UNIX for learning the concepts.

Ø The X Window System. The X Window System is the de facto industry-standard graphicssystem for UNIX machines. A complete version of the X Window system, known as XFree86,is available for Linux. The X Window System is a very powerful graphics interface, supportingmany applications.

Ø TCP/IP (Transmission Control Protocol/Internet Protocol) support. This is the set of protocolsthat links millions of university and business computers into a worldwide network known asthe Internet. With an Ethernet connection, you can have access to the Internet or to a localarea network from your Linux system. Using SLIP (Serial Line Internet Protocol) or PPP(Point to Point Protocol), you can access the Internet over phone lines with a modem.

Ø Virtual memory and shared libraries. Linux can use a portion of your hard drive as virtualmemory, expanding your total amount of available RAM. Linux also implements sharedlibraries, allowing programs that use standard subroutines to find the code for these subroutinesin the libraries at runtime. This saves a large amount of space on your system; each applicationdoesn’t store its own copy of these common routines.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 12: MSIT 3A

MSIT 3A Linux Internals 13

Ø The Linux kernel uses no code from AT&T or any other proprietary source. Much of thesoftware available for Linux is free. In fact, a large number of utilities in Linux are developedby the GNU project at the Free Software Foundation in Cambridge, Massachusetts. However,Linux enthusiasts, hackers, programmers, and recently even commercial companies from allover the world have contributed to the growing pool of Linux software.

Ø Linux supports (almost) all of the features of commercial versions of UNIX. In fact, some ofthe features found in Linux may not be available on other proprietary UNIX systems.

Ø GNU software support. Linux supports a wide range of free software written by the GNUProject, including utilities such as the GNU C and C++ compiler, gawk, groff, and so on.Many of the essential system utilities used by Linux are GNU software.

Ø Linux is compatible with the IEEE POSIX.1 standard. Linux has been developed with softwareportability in mind, thus supporting many important features of other UNIX standards.

Ø Virtual memory support. Linux utilizes all of your system’s memory, without memory limitsor segmentation through the use of a virtual memory manager.

Ø Built-in support for networking, multitasking, and other features. You’ll see this touted as“New Technology” in systems such as Windows NT. In fact, UNIX (and now, Linux) hasimplemented this “new technology” for more than 15 years.

Ø Linux is cheaper to get than most commercially available UNIX systems and UNIX clones.If you have the patience and access to the Internet, the only price you pay for Linux is yourtime. Linux is freely available on the Internet.

1.2 UNIX SYSTEM ARCHITECTUREØ The shell and the window environment are programs.

Ø Programs’ only access to hardware is via the kernel.

Ø Kernel understands only system calls, but not user commands.

Ø Shell converts user commands to system calls and pass on to the kernel.

Ø Kernel is the core part of Linux, hence it is also called the operating system.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 13: MSIT 3A

Chapter 1 - Introduction14

1.3 UNIX PHILOSOPHY

Fig. 1.1 Unix Architecture

Ø Multi-user.

♦ A user needs an account to use a computer.

♦ Each user must log in.

♦ Complete separation of different users’ files and configuration settings.

Ø Small components.

♦ Each component should perform a single task.

♦ Multiple components can be combined and chained together for more complex tasks.

♦ An individual component can be substituted for another, without affecting othercomponents.

1.4 WHAT IS LINUX?Ø Linux kernel.

♦ Developed by Linus Torvalds.

♦ Strictly speaking, ‘Linux’ is just the kernel.

Ø Associated utilities.

♦ Standard tools found on (nearly) all Linux systems.

♦ Many important parts come from the GNU project.

ð Free Software Foundation’s project to make a free Unix.

ð Some claim the OS as a whole should be ‘GNU/Linux’.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 14: MSIT 3A

MSIT 3A Linux Internals 15

Ø Linux distributions.

♦ Kernel plus utilities plus other tools, packaged up for end users.

♦ Generally with installation program.

♦ Distributors include: Red Hat, Debian, SuSE, Mandrake.

1.5 USING A LINUX SYSTEM: LOGINØ Login prompt displayed.

♦ When Linux first loads after booting the computer.

♦ After another user has logged out.

Ø Need to enter a username and password.

Ø The login prompt may be graphical or simple text.

Ø If text, logging in will present a shell.

Ø If graphical, logging in will present a desktop.

♦ Some combination of mouse key and keystrokes will make a terminal window appear.

♦ A shell runs in the terminal window.

1.6 LINUX COMMAND LINEØ The shell is where commands are invoked.

Ø A command is typed at a shell prompt.

♦ Prompt usually ends in a dollar sign ($)[bash Bourne again shell or sh Bourne shell].

Ø After typing a command press Enter to invoke it.

♦ The shell will try to obey the command.

♦ Another prompt will appear.

Ø Example:

$ date

Thu Jun 14 12:28:05 BST 2001

$

♦ The dollar represents the prompt in this course — do not type it.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 15: MSIT 3A

1.7 LOGGING OUTØ To exit from the shell, use the exit command.

Ø Pressing Ctrl+D at the shell prompt will also quit the shell.

Ø Quitting all programs should log you out.

♦ If in a text-only single-shell environment, exiting the shell should be sufficient.

♦ In a window environment, the window manager should have a log out command for thispurpose.

Ø After logging out, a new login prompt should be displayed.

1.8 COMMAND SYNTAXØ Most commands take parameters.

♦ Some commands require them.

♦ Parameters are also known as arguments.

♦ For example, echo simply displays its arguments:$ echo

$ echo Hello there Hello there

Ø Commands are case-sensitive.

♦ Usually lower-case.$ echo whisperwhisper$ ECHO SHOUTbash: ECHO: command not found.

1.9 FILESØ Data can be stored in a file.

Ø Each file has a filename.

♦ A label referring to a particular file.

Chapter 1 - Introduction16

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 16: MSIT 3A

♦ Permitted characters include letters, digits, hyphens (-), underscores (_), and dots (.)

♦ Case-sensitive — NewsCrew.mov is a different file from NewScrew.mov.

Ø The functions usually performed on a file are as follows:

v Opening a file for processing.

v Reading data from a file for processing.

v Writing data to a file after processing.

v Closing a file after all the necessary processing has been done.

1.10 LINUX DIRECTORIESØ As you probably already know from working in graphics mode, in Linux the directories use

the slash (/) as a separator (Windows uses backslash (\)). In other words it works just likewebsites or ftp servers.

Ø Any directory which starts with a slash, such as “/usr/bin”, means it is an “absolute” name- the name specifies the entire sequence of directories from the “root” directory (/) up to thespecific directory being requested (bin). Thus, it doesn’t matter which directory is the“current” directory when you specify that name, it will always point to the /usr/bin directory.

Ø On the other hand a directory which does not start with a slash is relative to the currentdirectory. For example the directory “bin” will point to different directories depending onwhether you are in the root directory (in which case it will point to “/bin”). It may reside inthe “/usr” directory (in which case it will point to /usr/bin) or in the “/usr/local” directory(in which case it will point to /usr/local/bin).

Ø The same applies to files - if you specify “file.txt” it is assumed to be in the current directory,while if you specify “/tmp/file.txt” it will always point to “file.txt” in the temporary directory.

Ø Two special directory names are the current directory, represented by a single period (.) andthe parent directory, represented by a double period (..). Thus, if you are in the /home/sandbox directory and type in ls .. , it will list the contents of the parent directory, which is/home.

1.11 FILE SYSTEM ORGANIZATIONØ In this section, you will learn about the ways LINUX provides for organizing files so that you

can easily locate and use them. LINUX has provided the directory as a way of organizingfiles. The directory is a special file under which you can have files or more directories (also

MSIT 3A Linux Internals 17

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 17: MSIT 3A

referred to as subdirectories). You can visualize the LINUX file structure as a bottom-uptree with the root at the top. Thus, the top-level directory is called the root directory and isdenoted by a single / (forward slash). All the directories and files belong to the root directory.

Ø Below is a list of some common directories that are found in Linux and Unix systems, andwhat they are used for.

Ø /

v This is the root directory, inside which all other directories reside

v This is similar to the root directory of a drive in Windows (C:\), except that in Linux evendifferent hard disks reside within this root.

Ø /bin

v This stands for “binary”, and contains program (executable) files. This (and other “bin”directories) is where commands such as “ls” can be found.

v In Windows, the c:\windows\commands holds some of command-line programs, but othersare scattered in various other directories.

Ø /dev

v This stands for “devices”. It contains a number of special pseudo-files that are used toaccess the physical hardware that make up, or are connected to, your computer. Forexample the parallel-port would be a file called “lp0” in this directory, while the hard diskwould be “hda”, and its first partition would be “hda0”.

v Windows / DOS uses a similar method, however in Windows these are not in any particulardirectory. Devices have names like LPT1, COM1 or CON - any time you try to accessa file with that name from any directory, you will get the parallel printer, serial port orconsole, respectively.

Ø /etc

v This is where (almost) all system-wide configuration information is stored. Almost allconfiguration information is stored in text files, so you can go into this directory and havea look around with a text viewer if you like. Some of the files are quite cryptic though.

v There is no equivalent in Windows, where configuration data can be stored anywhere,including the registry, INI files and other data files in various directories.

Ø /home

v This is where users’ home directories are usually found. Thus, if you created a usercalled “sandbox”, there will be a directory with the same name in this directory, which willbe that user’s home directory.

Chapter 1 - Introduction18

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 18: MSIT 3A

v The nearest equivalent in Windows is c:\windows\profiles, where some user-specificdata is held, together with c:\My Documents, where user-created documents go. Howeverother data can be written in many other directories.

Ø /lib

v This is where the library files are found. Libraries are files containing reusable functionsand routines for programs to use.

v There is no equivalent in Windows / DOS.

Ø /mnt

v This is where storage devices other than the hard disks are mounted. This directoryusually contains subdirectories called “cdrom”, “floppy”, etc., which - when these devicesare mounted - show the contents of the CD-ROM or floppy disk respectively. YourWindows drives may also be automatically mounted in this directory.

v There is no equivalent in Windows / DOS.

Ø /opt

v This is where optional components of the system are installed. Products such as KDE,Gnome and Oracle may be installed into this directory.

v The nearest thing in Windows is the c:\Program Files directory.

Ø /tmp

v This is a temporary directory. All files placed in here will automatically be deletedeventually.

v The equivalent in Windows / DOS is c:\windows\temp.

Ø /usr

v Contains a copy of most of the directories in the root. For example, there is a “bin”directory containing programs, a “lib” directory containing libraries, etc. Usually, “core”Linux files are contained in the root directories, while “non-core” files are in the “/usr”subdirectories.

v There is no equivalent in Windows / DOS.

Ø /var

v Stands for “various”. Among the files stored here are the system log files, spool filesand other data files.

v There is no equivalent in Windows / DOS.

MSIT 3A Linux Internals 19

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 19: MSIT 3A

1.12 CREATING FILES WITH CATØ There are many ways of creating a file.

Ø One of the simplest is with the cat command:

$ cat > shopping_list

cucumber

bread

milk

fish fingers

Ø Note the greater-than sign (>) — this is necessary to create the file.

Ø The text typed is written to a file with the specified name.

Ø Press Ctrl+D after a line-break to denote the end of the file.

♦ The next shell prompt is displayed.

Ø ls demonstrates the existence of the new file.

1.13 DISPLAYING FILES’ CONTENTS WITH CATØ There are many ways of viewing the contents of a file.

Ø One of the simplest is with the cat command:

$ cat shopping_list

cucumber

bread

milk

fish fingers

Ø Note that no greater-than sign is used.

Ø The text in the file is displayed immediately:

♦ Starting on the line after the command.

♦ Before the next shell prompt.

Chapter 1 - Introduction20

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 20: MSIT 3A

1.14 DELETING FILES WITH RMØ To delete a file, use the rm (‘remove’) command.

Ø Simply pass the name of the file to be deleted as an argument:

$ rm shopping_list

Ø The file and its contents are removed.

♦ There is no recycle bin.

♦ There is no ‘unrm’ command.

Ø The ls command can be used to confirm the deletion.

1.15 UNIX COMMAND FEEDBACKØ Typically, successful commands do not give any output.

Ø Messages are displayed in the case of errors.

Ø The rm command is typical.

♦ If it manages to delete the specified file, it does so silently.

♦ There is no ‘File shopping_list has been removed’ message.

♦ But if the command fails for whatever reason, a message is displayed.

Ø The silence can be be off-putting for beginners.

Ø It is standard behaviour, and doesn’t take long to get used to.

1.16 COPYING AND RENAMING FILES WITH CP AND MVØ To copy the contents of a file into another file, use the cp command:

$ cp CV.pdf old-CV.pdf

Ø To rename a file use the mv (‘move’) command:

$ mv commitee_minutes.txt committee_minutes.txt

♦ Similar to using cp then rm.

Ø For both commands, the existing name is specified as the first argument and the new nameas the second.

♦ If a file with the new name already exists, it is overwritten.

MSIT 3A Linux Internals 21

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 21: MSIT 3A

1.17 FILENAME COMPLETIONØ The shell can make typing filenames easier.Ø Once an unambiguous prefix has been typed, pressing Tab will automatically ‘type’ the rest.Ø For example, after typing this:

$ rm shopressing Tab key (key board) may turn it into this:$ rm shopping_list

Ø This also works with command names.♦ For example, da may be completed to date if no other commands start ‘da’.

1.18 COMMAND HISTORYØ Often it is desired to repeat a previously executed command.Ø The shell keeps a command history for this purpose.

♦ Use the Up and Down cursor keys to scroll through the list of previous commands.♦ Press Enter to execute the displayed command.

Ø Commands can also be edited before being run.♦ Particularly useful for fixing a typo in the previous command.♦ The Left and Right cursor keys navigate across a command.♦ Extra characters can be typed at any point.♦ Backspace deletes characters to the left of the cursor.♦ Del and Ctrl+D delete characters to the right.ð Take care not to log out by holding down Ctrl+D too long.

1.19 SUMMARYAn operating system is an important part of a computer system. You can view a computer system as

being built from three general components: the hardware, the operating system, and the applications. Thehardware includes pieces such as a central processing unit (CPU), a keyboard, a hard drive, and a printer.You can think of these as the parts you are able to touch physically. Applications are why you usecomputers; they use the rest of the system to perform the desired task (for example, play a game, edit amemo, send electronic mail). The operating system is the component that on one side manages andcontrols the hardware and on the other manages the applications.

Chapter 1 - Introduction22

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 22: MSIT 3A

The operating system controls all the resources of the computer system and that control is given to theuser. The user runs his applications to achieve the goal.

1.20 CHECK YOUR PROGRESS

I. Exercises

1. a. Log in.

b. Log out.

c. Log in again. Open a terminal window, to start a shell.

d. Exit from the shell; the terminal window will close.

e. Start another shell. Enter each of the following commands in turn.

ð dateð whoamið hostnameð unameð uptime

2. a. Use the ls command to see if you have any files.

b. Create a new file using the cat command as follows:

$ cat > hello.txt

Hello world!

This is a text file.

Press Enter at the end of the last line, then Ctrl+D to denote the end of the file.

c. Use ls again to verify that the new file exists.

d. Display the contents of the file.

e. Display the file again, but use the cursor keys to execute the same command againwithout having to retype it.

3. a. Create a second file. Call it secret-of-the-universe, and put in whatever content youdeem appropriate.

b. Check its creation with ls.

MSIT 3A Linux Internals 23

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 23: MSIT 3A

c. Display the contents of this file. Minimise the typing needed to do this:

ð Scroll back through the command history to the command you used to create the file.

ðChange that command to display secret-of-the-universe instead of creating it.

4. After each of the following steps, use ls and cat to verify what has happened.

a. Copy secret-of-the-universe to a new file called answer.txt. Use Tab to avoid typing theexisting file’s name in full.

b. Now copy hello.txt to answer.txt. What’s happened now?

c. Delete the original file, hello.txt.

d. Rename answer.txt to message.

e. Try asking rm to delete a file called missing. What happens?

f. Try copying secret-of-the-universe again, but don’t specify a filename to which tocopy. What happens now?

II. Choose the correct answer:1. Linux is invented by_________.

a) Linus Torvalds b) Dennis Ritchie c) James Gosling d)None of these.

2. Operating system is a collection of _______________.

a) S/w programs b) system programs c) Application programs d) all of these.

3. Linux components include the __________.

a) Kernel b) shell c) file system & user programs d) all of these.

4. NFS means _________________________.

a) Network File System

b) Network FAT System

c) NetBios System

d) None of the above

5. Device Drivers control the interaction between the _________________.

a) I/p device & operating system

b) Operating system & o/p device

Chapter 1 - Introduction24

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 24: MSIT 3A

c) Operating system & hardware device

d) All of the above

6. The standard way of mounting file systems onto the _________ directory.

a) dev b) mnt c) bin d) all of these

7. Linux supports ___________ file systems.

a) Single b) NFS c) multiple d) all of these

8. Linux support __________.

a) multitasking only

b) 32-bit

c) Networking

d) All of the above.

9. In Linux the directories uses the ____ as a separator.

a) / b) \ c) // d) all of these

10. shell is a ___________.

a) command interpreter

b) operating system

c) system call

d) All of the above

III. Say True or False1. Linux is a 16-bit operating system. True/False

2. Linux is a multi-processor operating system. True/False

3. Linux supports many different file systems. True/False

4. Block size for floppy device is 1024 bytes. True/False

5. KERNEL accepts instructions from the shell and carries them out True/False

MSIT 3A Linux Internals 25

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 25: MSIT 3A

IV. Essay Type Questions1) What is Linux? Write brief features regarding Linux.

2) Explain the architecture of Unix.

3) Explain the concept of filesystem.

4) Elucidate the functions usually performed on a file.

5) Explain how the directories are manipulated in Linux.

6) Describe how the file systems are arranged? Give the types.

7) Exhibit the commands for login, logoff & switching to another account.

8) Enumerate the commands related to file retrivals.[ Ex: cat, rm, cp, mv ]

V. Further readings and other activities1. The student shall get more information using man or info or any other help command for

pwd, mkdir, cd, rmdir, sh, csh, ksh

Ex: man pwd OR info ls OR —help cd OR apropos cp

2. Get new commands from the list given at the end of any man command information at theplace see also.

3. Using man intro, get the information about different kinds of commands present in your kindof linux system.

4. For further readings you can refer the following books

Ø Title: Linux internals

Auihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.pandurangarao.i8.com/doc/linux/linuxbook.html

http://www.raomvp.bravepages.com/doc/linux/linuxbook.html

A complete reference for you to get more information.

You can also extract solutions for exercises.

Ø Title: Linux in a Nutshell

Author: Jessica Perry Hekman and the staff of O’Reilly & Associates; ISBN 1-56592-167-4; 1997. A complete reference for Linux.

Ø Title: Harley Hahn’s Student Guide to UNIX, second edition; McGraw- Hill; ISBN 0-07-025492-3; 1996. Not just for students, this is a complete and very readable guide toLINUX and networking.

Chapter 1 - Introduction26

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 26: MSIT 3A

VI. Solutions

II. Choose the correct answer:II. 1. a 2. b 3. d 4. a 5. d 6. b 7. d 8. d 9. a 10. a

III. Say True or FalseIII 1. false 2. true 3. true 4. false 5. true

MSIT 3A Linux Internals 27

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 27: MSIT 3A

Chapter 2 - Linux Commands28

Chapter 2

Linux Commands

2.0 INTRODUCTION AND OBJECTIVES

Linux is a complete multitasking, multi-user operating system that behaves like the UNIX operatingsystem in terms of kernel behavior and peripheral support. Linux has all the features of UNIX,plus several recent extensions that add new versatility to Linux. All source code for Linux and its

utilities is freely available.

The Linux kernel was originally developed for the Intel 80386 CPU’s protected mode. The 80386 wasdesigned with multitasking in mind (despite the fact that most of the Intel CPUs are used with single-tasking DOS), and Linux makes good use of the advanced features built into the CPU’s instruction set.Memory management is especially strong with the 80386 (compared to earlier CPUs). A floating-pointemulation routine allows Linux to function on machines that do not have math coprocessors (such as theSX series of Intel CPUs).

Linux allows shared executables so that if more than one copy of a particular application is loaded(either by one user running several identical tasks, or several users running the same task), all the taskscan share the same memory. This process, called copy-on-write pages, makes for much more efficientuse of RAM.

The Linux kernel also supports demand paging, which means that only sections of a program that arenecessary are read into RAM. To further optimize memory usage, Linux uses a unified memory pool.This pool enables all free memory on the system to be used as disk cache, effectively speeding up accessto frequently used programs and data. As memory usage increases, the amount of cache is automaticallyadjusted.

To support large memory requirements when only small amounts of physical RAM are available,Linux supports swap space. Swap space enables pages of memory to be written to a reserved area of a

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 28: MSIT 3A

MSIT 3A Linux Internals 29

disk and treated as an extension of physical memory. By moving pages back and forth between the swapspace and RAM, Linux can effectively behave as if it had more physical RAM than it does, albeit at thecost of some speed due to the hard drive’s slower access.

Linux uses dynamically shared libraries extensively. Dynamically shared libraries use a common librarysection for many different applications, effectively reducing the size of each application. Linux does allowfull library linking (called statically linked libraries) for portability to machines that may not have thedynamic libraries.

To make Linux widely acceptable, it supports a number of different filesystems, including thosecompatible with DOS and OS/2. Linux’s own primary filesystem, called ext2fs, is designed for optimaluse of the disk.

Linux is ideally suited for application development and experimentation with new languages. Severaldifferent compilers, including C, C++, Fortran, Pascal, Modula-2, LISP, Ada, Basic, and Smalltalk, comewith the distribution software. Many of the Linux compilers, tools, debuggers, and editors are from theFree Software Foundation’s GNU project.

After completing this module you should be able to understand and utilize these features of the Linuxcommands:

ð Basic Linux commands

ð Help commands

ð General commands

ð File management commands

ð Finding files

ð Linux files and file Permission

ð File names and permission characters

ð Example to extract information from files

ð Setting keystrokes

ð Keys and terminal configuration

2.1 BASIC LINUX COMMANDSØ A UNIX command is a series of characters that we type.

Ø To invoke a command, simply type the command name, followed by arguments (if any), toindicate to the shell that we are done typing and are ready for the command to be executed,press Enter.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 29: MSIT 3A

Chapter 2 - Linux Commands30

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 30: MSIT 3A

MSIT 3A Linux Internals 31

2.2 HELP COMMANDSØ any_command —help | more

Display a brief help on a command (works with most commands). For example, try

cp —help |more

“—help” works similar to DOS “/h” switch. The “more” pipe is needed when the output islonger than one screen.

Ø man topic

Display the contents of the system manual pages (help) on the topic. Press “q” to quit theviewer. Try man man if we need any advanced options. The command info topic workssimilar to man topic, yet it may contain more up-to-date information. Manual pages can behard to read—they were written for UNIX programmers. Try any_command —help for abrief, easier to digest help on a command. Some programs also come with README or

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 31: MSIT 3A

other info files—have a look to the directory /usr/share/doc. To display manual page from aspecific section, We may use something like: man 3 exit (this displays an info on the commandexit from section 3 of the manual pages) or man -a exit (this displays man pages for exit fromall sections). The man sections are: Section 1-User Commands, Section 2-System Calls,Section 3-Subroutines, Section 4-Devices, Section 5-File Formats, Section 6-Games, Section7-Miscellaneous, Section 8-System Administration, Section 9, Section n-New.

Ø info topic

Display the contents of the info on a particular command. info is a replacement for manpages so it contains the most recent updates to the system documentation. Use <Space> and<BkSpace> to move around or we may get confused. Press “q” to quit. A replacement forthe somewhat confusing info browsing system might be pinfo - try if we like it any better.

Ø apropos topic

Give me the list of the commands that have something to do with my topic. If does not workrun $ updatedb as root.

Ø whatis topic

Give me a short list of commands matching my topic. whatis is similar to apropos (see thecommand above)—they both use the same database. But whatis searches keywords, whileapropos also searches the descriptions of the keywords.

Ø help command

Display brief info on a bash (shell) built-in command. Using help with no command prints thelist of all bash built-in commands. The shortest list of bash built-in commands would probablyinclude: alias, bg, cd, echo, exit, export, fg, help, history, jobs, kill, logout, pwd, set, source,ulimit, umask, unalias, unset.

Ø kdehelpcenter &

(in X-terminal). Browse the whole system help using the graphical KDE help navigator.Normally, KDE help is invoked by pressing the appropriate icon on the KDE control panel.Use gnome-help-browser for the GNOME equivalent. (The older KDE versions usedkdehelp& instead of kdehelpcenter&).

2.3 GENERAL COMMANDSØ pwd

Print working directory, i.e., display the name of my current directory on the screen.

Chapter 2 - Linux Commands32

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 32: MSIT 3A

Ø hostnamePrint the name of the local host (the machine on which We are working). Use netconf (asroot) to change the name of the machine.

Ø whoami

Print my login name.

Ø id username

Print user id (uid) and his/her group id (gid), effective id (if different than the real id) and thesupplementary groups.

Ø who

Determine the users logged on the machine.

Ø last

Show listing of users last logged-in on the system. Really good idea to check it from time totime as a security measure on our system.

Ø history | more

Show the last (1000 or so) commands executed from the command line on the currentaccount. The “| more” causes the display to stop after each screen. To see what anotheruser was doing on the system, login as “root” and inspect his/her “history”. The history iskept in the file .bash_history in the user home directory.

Ø uname -a

(= “Unix name” with option “all”) Info on our (local) server. We can also use guname (in X-window terminal) to display the info more nicely.

Ø free

Memory info (in kilobytes). “Shared” memory is the memory that can be shared betweenprocesses (e.g., executable code is “shared”). “Buffered” and “cashed” memory is the partthat keeps parts of recently accessed files—it can be shrunk if more memory is needed byprocesses.

Ø set

Show the current user environment (in full).

Ø echo $PATH

Show the content of the environment variable “PATH”. This command can be used to showother environment variables as well. Use set to see the full environment.

MSIT 3A Linux Internals 33

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 33: MSIT 3A

Ø ls or dir

List the contents of the current directory. The command dir is an alias to ls so these twocommands do exactly the same thing. The file listing is normally color-coded: dark blue=directories, light grey = regular files, green = executable files, magenta = graphics files, red= compressed (zipped) files, light blue = symbolic links, yellow = device files, brown = FIFO(“First-In First-Out” named pipes).

Ø ls -al |more

List the content of the current directory, all files (also those starting with a dot), and in a longform. Pipe the output through the “more” command, so that the display pauses after eachscreenful. The ls command has several very useful options. Some of these may have shortcuts(aliases) to avoid clumsy typing. Try ll (=”long ls”, an alias to ls -l). Another option We usequite often is ls-ad (list all the subdirectories in my current directory, but don’t list theircontents).

Ø cd directory

Change directory. Using “cd” without the directory name will take us to our home directory.“cd - “ will take us to our previous directory and is a convenient way to toggle between twodirectories. “cd ..” will take me one directory up (very useful).

Ø shutdown -h now

(as root) Shut down the system to a halt. Mostly used for a remote shutdown. Use<Ctrl><Alt><Del> for a shutdown at the console (which can be done by any user).

Ø halt or reboot or init 6

(as root, three commands) Halt or reboot the machine. Used for remote shutdown, simplerto type than the previous command. Also great if the computer “hangs” (if we lose controlover the keyboard)—We can telnet to it from another machine on the network and remotelyreboot it. We use <Ctrl><Alt><Del> for normal shutdown at the console of a local computer.

2.4 FILE MANAGEMENT COMMANDSØ rm files

Remove (delete) files. We must own the file in order to be able to remove it (or be “root”).On many systems, We will be asked for a confirmation of deletion; if We don’t want this, usethe “- f” (=force) option, e.g., rm -f * will remove all files in my current working directory, noquestions asked.

Ø mkdir directory

Make a new directory.

Chapter 2 - Linux Commands34

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 34: MSIT 3A

Ø rmdir directory

Remove an empty directory.

Ø rm -r files

(recursive remove) Remove files, directories, and their subdirectories. Careful with thiscommand as root—We can easily remove all files on the system with such a commandexecuted on the top of our directory tree, and there is no undelete in Linux (yet). But if Wereally wanted to do it (reconsider), here is how (as root): rm -rf /*

Ø rm -rf files

(recursive force remove). As above, but skip the prompt for confirmation, if one is set on oursystem. Careful with this command particularly as root—see the command above.

Ø cat filename | more

View the content of a text file called “filename”, one page a time. The “|” is the “pipe”symbol (on many American keyboards it shares the key with “\”). more makes the outputstop after each screenful. For long files, it is sometimes convenient to use the commandshead and tail that display just the beginning and the end of the file, or less that enablesscrolling up and down. If we happened to use cat a binary file and our terminal displaysfunny characters afterwards, we can restore it with the command reset.

Ø cat filename | less, less filename

(two commands, use either) Scroll a content of a text file. Press q when done. “less” isroughly an equivalent to “more” , the command we know from DOS, but often “less” is moreconvenient than “more” because it lets me scroll both up and down.

Ø head filename

Print first 10 lines of the (long) text file.

Ø tail filename

Print last 10 lines of a long or growing text file. Use tail -f filename for tail to follow the fileas it grows—really handy for continuing inspection of log files.

Ø ispell filename

Spell check an ASCII text file. AbiWord, WordPerfect, StarOffice and other word processorscome with “as-we-type” spellchecking, so we really don’t have to worry about the simpleispell unless we need it.

Ø touch filename

Change the date/time stamp of the file filename to the current time. Create an empty file ifthe file does not exist. You can change the stamp to any date using touch -t 200201311759.30(year 2002 January day 31 time 17:59:30).

MSIT 3A Linux Internals 35

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 35: MSIT 3A

There are three date/time values associated with every file on an ext2 filesystem:

- the time of last access to the file (atime)

- the time of last modification to the file (mtime)

- the time of last change to the file’s inode (ctime).

Touch will change the first two to the value specified, and the last one always to the currentsystem time. They can all be read using the stat command.

Ø stat filename

Print general info about a file (the contents of the so-called inode).

Ø strings filename | more

Display the strings contained in the binary file called filename. “strings” could, for example,be a useful first step to a close examination of an unknown executable.

Ø od

(=octal dump). Display contents as octal numbers. This can be useful when the output containsnon-printable characters. For example, a filename may contain non-printable characters andbe a real pain. This can also be handy to view binary files.

Examples: dir | od -c | more

Ø sort -f filename

Arrange the lines in filename according to the ascii order. The option -f tells sort to ignorethe upper and lower character case.

Ø uniq

(=unique) Eliminate duplicate lines in sorted input. Example: sort myfile | uniq

Ø fold -w 30 -s my_file.txt > new_file.txt

Wrap the lines in the text file my_file.txt so that there is 30 characters per line. Break thelines on spaces. Output goes to new_file.txt.

Ø rev filename > filename1

Print the file filename, each line in reversed order. In the example above, the output isdirected to the file filename1.

Ø paste file1 file2 > file3

Merge two or more text files on lines using <Tab> as delimiter (use option “d=” to specifyour own delimiter(s).

Chapter 2 - Linux Commands36

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 36: MSIT 3A

Ø join file1 file2 > file3

Join lines of two files on a common field. join parallels the database operation “join tables”,but works on text tables. The default is to join on the first field of the first table, and thedefault delimiter is white space.

2.5 FINDING FILESØ find / -name “filename”

Find the file called “filename” on our filesystem starting the search from the root directory “/”. The “filename” may contain wildcards (*,?).

Ø locate filename

Find the file name which contains the string “filename”. Easier and faster than the previouscommand but depends on a database that normally rebuilds at night, so we cannot find a filethat was just saved to the filesystem. To force the immediate update of the database, Wemay do (as root): updatedb&.

Ø which executable_name

Show me the full path to the executable that would run if we just typed its name on thecommand line. For example, this command:

Ø whereis command

Print the locations for the binary, source, and manual page files of the command “command”.

2.6 LINUX FILES AND FILE PERMISSIONØ Linux files are setup so access to them is controlled. There are three types of access:

1. read2. write3. execute

Ø Each file belongs to a specific user and group. Access to the files is controlled by user, group,and what is called other. The term, other, is used to refer to someone who is not the user(owner) of the file, nor is the person a member of the group the file belongs to. When talkingabout setting permissions for “other” users to use, it is commonly referred to as setting theworld execute, read, or write bit since anyone in the world will be able to perform theoperation if the permission is set in the other category.

MSIT 3A Linux Internals 37

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 37: MSIT 3A

2.7 FILE NAMES AND PERMISSION CHARACTERSØ File names can be up to 256 characters long with “-”, “_”, and “.” characters along with

letters and numbers. When a long file listing is done , there are 10 characters that are shownon the left that indicate type and permissions of the file. File permissions are shown accordingto the following syntax example: drwxrwxrwx

Ø There are a total of 10 characters in this example for all Linux / Unix files. The first characterindicates the type of file, and the next three indicate read, write, and execute permission foreach of the three user types, user, group and other. Since there are three types of permissionfor three users, there are a total of nine permission bits. The table below shows the syntax:

v Character 1 is the type of file: - is ordinary, d is directory, l is link.

v Characters 2-4 show owner permissions. Character 2 indicates read permission,character 3 indicates write permission, and character 4 indicates execute permission.

v Characters 5-7 show group permissions. Character 5=read, 6=write, 7=execute

v Characters 8-10 show permissions for all other users. Character 8=read, 9=write,10=execute

Ø There are 5 possible characters in the permission fields. They are:

ð r = read - This is only found in the read field.

ð w = write - This is only found in the write field.

ð x = execute - This is only found in the execute field.

ð s = setuid - This is only found in the execute field.

ð If there is a “-” in a particular location, there is no permission. This may be found in anyfield of read, write, or execute.

2.8 EXAMPLES ON FILESØ Type “ls -l” and a listing like the following is displayed:

Chapter 2 - Linux Commands38

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 38: MSIT 3A

total 10drwxrwxrwx 4 george team1 122 Dec 12 18:02 Projects-rw-rw-rw- 1 george team1 1873 Aug 23 08:34 test-rw-rw-rw- 1 george team1 1234 Sep 12 11:13 datafile

ð Which means the following:

Ø The fields are as follows:

1. Type field: The first character in the field indicates a file type of one of the following:

ð d = directory

ð l = symbolic link

ð s = socket

ð p = named pipe

ð - = regular file

ð c= character (un buffered) device file special

ð b=block (buffered) device file special

2. Permissions are explained above.

3. Links: The number of directory entries that refer to the file. In our example, there are four.

4. The file’s owner in our example is George.

5. The group the file belongs to. In our example, the group is team1.

6. The size of the file in bytes

7. The last modification date. If the file is recent, the date and time is shown. If the file is not inthe current year, the year is shown rather than time.

8. The name of the file.

MSIT 3A Linux Internals 39

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 39: MSIT 3A

2.9 SETTING KEYSTROKESØ The stty command - Used to set up keystrokes on terminals [try $ stty –a].

The command <stty erase “^H”> will bind the Backspace key(^H) to the erase function.

Characters that are specified:

v eof - End of file

v eol - End of line

v eol2 - Alternate character for ending a line

v erase - Erase the last character typed

v intr - The specified character will send an interrupt signal

v kill - Erase the current line.

v quit - Sends a quit signal.

v start - Restart output after having stopped it.

v stop - Stops the output.

v susp - Sends a terminal stop signal

v switch - Switch to a different shell layer

v werase - erase the last word typed.

setterm –foreground white – Sets white foreground, and bluebackground blue background

setterm –store Stores the present terminal values as default

2.10 KEYS AND TERMINAL CONFIGURATIONØ Special command line keys:

v CTRL U - Delete the linev CTRL C - Abort commandv CTRL Z - Suspend command, Type fg to put it back into the foregroundv <TAB> - Auto complete commandv <ALT>F1 through <ALT>F6 - Select a different virtual terminal

Chapter 2 - Linux Commands40

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 40: MSIT 3A

v <CRTL><ALT>F7 - Toggle to the first X terminal, if one is running.v <CRTL><ALT>F1 - Toggle to the first text terminal from an X session.v CTRL D - End of file, exits the shellv CTRL W - Delete a word backwardsv CTRL / - Quit, weaker than CTRL C but does a core dump.v CTRL S - Stop scrolling, may use “scroll lock” for this function.v CTRL Q - Resume scrolling

2.11 SUMMARYØ A UNIX command is a series of characters that we type. These characters consist of words

that are separated by whitespace. Whitespace is the result of typing one or more Space orTab keys. The first word is the name of the command. The rest of the words are called thecommand’s arguments.

Ø The arguments give the command information that it might need, or specify varying behaviorof the command. You can use command options to fine-tune the actions of a Linux command.

Ø Quite often, a Linux command will do almost, but not quite what you want it to do. Instead ofmaking you learn a second command, Linux lets you modify the basic, or default, actions ofthe command by using options.

Ø Most Linux commands are very flexible. When you enter a Linux command, there areseveral ways to tailor the basic command to your specific needs. We will look at the twomain ways used to modify the effect of a command:

v Specifying or redirecting a command’s input and output

v Using command options

Ø Standard LINUX commands makes shell scripts more versatile. The power of scripts comesfrom coupling system commands and shell directives with simple programming constructs.

2.12 CHECK YOUR PROGRESS

I. ExercisesManipulating files

In this exercise, we’ll create, rename and delete files. Find out if the system has one or more printersas well as the appropriate command to use for printing.

MSIT 3A Linux Internals 41

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 41: MSIT 3A

Go to home directory. Enter cd

Copy distant file to working directory. Enter cp /etc/passwd myfile

Create new directory. Enter mkdir temp

List working directory. Enter ls –F

Move file to new directory. Enter mv myfile temp

Change working directory. Enter cd temp

Copy file to working directory. Enter cp myfile myfile.two

Print the file. Enter the printer command and the filename

List filenames with wildcard. Enter ls -l myfile*

Remove files. Enter rm myfile*

Go up to parent directory. Enter cd ..

Remove directory. Enter rmdir temp

Verify that directory was removed. Enter ls –F

II. Choose the correct answer:1) tac _______________________.

a) concatenates 2 files

b) listing a file backwards from its end

c) reverses each line of file

d) none of the above

2) rmdir remove directory iff _____________.

a) Directory must be empty of all files

b) Directory mayn’t be empty

c) Both a) & b)

d) None of the above

Chapter 2 - Linux Commands42

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 42: MSIT 3A

3) touch command is used for ____________.

a) Updating access/modification times of a file to current system time

b) Creating a new file

c) Both a) & b)

d) None of the above

4) Diff reports ____________________

a) Differences between two files

b) At what point the files differ

c) Removes duplicate lines

d) None of the above.

5) egrep an acronym for __________________________.

a) evaluation global regular expression print

b) extensible global regular expression print

c) extended global regular expression print

d) none of the above.

6) traceroute works within ______

a) LAN

b) WAN

c) Over the internet

d) All of the above

7) If finger is used without an argument ___________________________

a) it gives information concerning users currently logged in

b) it gives information about a particular user on a network

c) it gives information about all users

d) none of the above

MSIT 3A Linux Internals 43

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 43: MSIT 3A

8) Protocol used for connecting to a remote host _______.

a) ftp

b) telnet

c) tcp/ip

d) none of the above

9) df command is used for__________ purpose.

a) Communication

b) System & administrative

c) Networking

d) File & archiving

10) Command used for shutting down the system ______

a) halt

b) exit

c) quit

d) logout

11) The following are Network related Commands _______

a) Wall

b) ftp

c) host

d) none of the above

Chapter 2 - Linux Commands44

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 44: MSIT 3A

III. Say True or False1. mv is equivalent to a combination of cp & rm True/False

2. mkdir –p creates a new directory with necessary parent directories. True/False

3. expr concatenates and evaluates the arguments according to the givenoperation True/False

4. join pastes together only those lines with a common numerical label. True/False

5. tr a-z \* < filename changes all the lowercase letters in filename to asterisks True/False

6. exec shell builtin replaces the present process with a specified command. True/False

7. kill command resumes a process. True/False

IV. Essay Type Questions1. Write a short notes on the following with relevant options.

a. cat & tac

b. chmod

c. touch

d. sort

e. grep

2. Explain any three help, file and text Processing Commands.

3. Write in detial about tar command with the relvant options.

4. Give the differentiation between locate, find & slocate.

5. Give a short note on the following communication commands.

a. cat

b. rm

6. List the differences between the following.

a. mv & cp

b. tac & rev

c. expr & let

d. cmp & diff

MSIT 3A Linux Internals 45

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 45: MSIT 3A

V. Further readings and other activities1. Get more information using man or info or any help command for find, date, uniq, stty, diff,

cmp, ls

EX: 1. $ man du 2. $ apropos bash

Check the amount of space used, amount of space free for different drives and differentdirectories.

2. For further readings you can refer the following books

Ø Title: Linux internals

Auihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.pandurangarao.i8.com/doc/linux/linuxbook.html

http://www.raomvp.bravepages.com/doc/linux/linuxbook.html

A complete reference for you to get more information.

You can also extract solutions for exercises.

Ø Title: principles of unix programming

Auihors: Sumitabha Das

Ø Work and expertise all the commands given in the chapter with different options and by thevirtue of which know, which command is to be used for different situations of jobs.

VI. Solutions

II. Choose the correct answer:1.b 2.a 3.c 4.a 5.c 6.d 7.b 8.b 9.b 10.a 11.d

III. Say True or False1.True 2.True 3.True 4.True 5.True 6.True 7.False

Chapter 2 - Linux Commands46

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 46: MSIT 3A

MSIT 3A Linux Internals 47

Chapter 3

Processes

3.0 INTRODUCTION AND OBJECTIVES

A running instance of a program is called a PROCESS. If we have two terminal windows showingon our screen, then we are probably running the same terminal program twice—we have twoterminal processes. Each terminal window is probably running a shell; each running shell is

another process. When we invoke a command from a shell, the corresponding program is executed in anew process; the shell process resumes when that process completes.

Advanced programmers often use multiple cooperating processes in a single application to enable theapplication to do more than one thing at once, to increase application robustness, and to make use ofalready-existing programs.

Most of the process manipulation functions described in this chapter are similar to those on otherUNIX systems. Most are declared in the header file <unistd.h>; check the man page for each function tobe sure.

ObjectivesAfter completing this module you should be able to understand and utilize these features of the Linux

processes:

ð Looking at processesð Process IDsð Analysis of active processesð Different output formats of ps

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 47: MSIT 3A

ð Killing a processð Processes creation mechanismsð Using system, system calls - fork, execð Calling fork, using the exec Familyð Using fork and exec Togetherð Process schedulingð Signals and Linux daemonsð Most useful daemonsð Zombie process and threadsð Differentiating processes and threads

3.1 LOOKING AT PROCESSESØ Even as we sit down at our computer, there are processes running. Every executing program

uses one or more processes. Let’s start by taking a look at the processes already running onthe computer.

3.2 PROCESS IDSØ Each process in a Linux system is identified by its unique process ID, sometimes referred to

as pid. Process IDs are 16-bit numbers that are assigned sequentially by Linux as newprocesses are created.

Ø Every process also has a parent process. Thus, we can think of the processes on a Linuxsystem as arranged in a tree, with the init process at its root. The parent process ID, orppid, is simply the process ID of the process’s parent.

Ø When referring to process IDs in a C or C++ program, always use the pid_t typedef, whichis defined in <sys/types.h>.A program can obtain the process ID of the process it’s runningin with the getpid() system call, and it can obtain the process ID of its parent process withthe getppid() system call. For instance, the program in Listing below prints its process IDand its parent’s process ID.

Ø Listing ( print-pid.c) Printing the Process ID

#include <stdio.h>#include <unistd.h>int main ()

Chapter 3 - Processes48

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 48: MSIT 3A

{printf (“The process ID is %d\n”, (int) getpid ());printf (“The parent process ID is %d\n”, (int) getppid ());return 0;}

Ø Observe that if we invoke this program several times, a different process ID is reportedbecause each invocation is in a new process. However, if we invoke it every time from thesame shell, the parent process ID (that is, the process ID of the shell process) is the same.

3.3 VIEWING ACTIVE PROCESSESØ The ps command displays the processes that are running on our system. The Linux version

of ps has lots of options because it tries to be compatible with versions of ps on several otherUNIX variants. These options control which processes are listed and what information abouteach is shown.

Ø By default, invoking ps displays the processes controlled by the terminal or terminal windowin which ps is invoked. For example:

$ psPID TTY TIME CMD21693 pts/8 00:00:00 bash21694 pts/8 00:00:00 ps

Ø This invocation of ps shows two processes. The first, bash, is the shell running on thisterminal. The second is the running instance of the ps program itself. The first column,labeled PID, displays the process ID of each.

Ø For a more detailed look at what’s running on our Linux system, invoke this:

$ ps -e -o pid,ppid,command

Ø The -e option instructs ps to display all processes running on the system. The -opid,ppid,command option tells ps what information to show about each process— in thiscase, the process ID, the parent process ID, and the command running in this process.

3.4 PS OUTPUT FORMATSØ With the -o option to the ps command, we specify the information about processes that we

MSIT 3A Linux Internals 49

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 49: MSIT 3A

want in the output as a comma-separated list. For example, ps -opid,user,start_time,command displays the process ID, the name of the user owning theprocess, the wall clock time at which the process started, and the command running in theprocess. See the man page for ps for the full list of field codes. We can use the -f (fulllisting), -l (long listing), or -j (jobs listing) options instead to get three different preset listingformats.

Ø Here are the first few line and last few lines of output from this command on the system. Wemay see different output, depending on what’s running on our system.

$ ps -e -o pid,ppid,command

PID PPID COMMAND1 0 init [5]2 1 [kflushd]3 1 [kupdate]...21725 21693 xterm21727 21725 bash21728 21727 ps -e -o pid,ppid,command

Ø Note that the parent process ID of the ps command, 21727, is the process ID of bash, theshell from which we invoked ps. The parent process ID of bash is in turn 21725, the processID of the xterm program in which the shell is running.

Ø Using ps provides us a snapshot of the system’s active processes. The following are thefields from the output of the ps command that are important in terms of performance tuning:

Field Description

F Flags that indicate the process’s current state and are calculated by adding eachof the hexadecimal values:

00 Process has terminated

01 System process, always in memory

02 Process is being traced by its parent

04 Process is being traced by parent, and is stopped

08 Process cannot be awakened by a signal

10 Process is in memory and locked, pending an event

20 Process cannot be swapped

S The current state of the process, as indicated by one of the following letters:

Chapter 3 - Processes50

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 50: MSIT 3A

O Process is currently running on the processor

S Process is sleeping, waiting for an I/O event (including terminal I/O) to complete

R Process is ready to run

I Process is idle

Z Process is a zombie process (it has terminated, and the parent is not waitingbut is still in the process table)

T Process is stopped because of parent tracing it

X Process is waiting for more memory

3.5 KILLING A PROCESSØ While logged in as root, type “ps -ax | more” or “ps -aux | more”. We will get a list of all

processes running on our computer. We will see the process id (PID), process status (STAT)various statistics, and the command name. We can kill a process by typing “kill” and thePID number right afterwards similar to the line below.$ kill 1721

Ø We can also stop and restart processes by sending them various signals as in the belowexamples:

kill –STOP 1721 Stops (suspends) process 1721 by sending the STOP signal to theprocess. This process will still be on the task list. The process can’tcatch or ignore the STOP signal.

kill –CONT 1721 Continue process 1721 causing it to resume. The CONT signal issent to the process.

kill –TERM 1721 Terminates process 1721 by sending the TERM signal to the process.This process will no longer show up on the task list if it is actuallyterminated. Process terminated cannot be continued. The TERMsignal can be caught so TERM is not guaranteed to kill the process.

kill –HUP 1721 Stops, then restarts process 1721. This is usually done when aprocess is not working properly or the configuration files for thatprocess have been changed. This command sends the HUP signalto the process which means hangup. This signal can be caught bythe process.

killall –HUP myprint Restarts any process with the name “myprint”.

kill –TERM myprint Terminates any process with the name “myprint”.

MSIT 3A Linux Internals 51

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 51: MSIT 3A

3.6 CREATING PROCESSESØ Two common techniques are used for creating a new process. The first is relatively simple

but should be used sparingly because it is inefficient and has considerably security risks. Thesecond technique is more complex but provides greater flexibility, speed, and security.

3.7 CREATING USING SYSTEM()

Ø The system function in the standard C library provides an easy way to execute a commandfrom within a program, much as if the command had been typed into a shell. In fact, systemcreates a sub process running the standard Bourne shell (/bin/sh) and hands the commandto that shell forexecution.

Ø For example, this program in Listing invokes the ls command to display the contents of theroot directory, as if we typed ls -l / into a shell.

Ø Listing (system.c) Using the system Call

#include <stdlib.h>

int main ()

{

int return_value;

return_value = system (“ls -l /”);

return return_value;

}

Ø The system function returns the exit status of the shell command. If the shell itself cannot berun, system returns 127; if another error occurs, system returns –1. Because the systemfunction uses a shell to invoke our command, it’s subject to the features, limitations, andsecurity flaws of the system’s shell.

Ø We can’t rely on the availability of any particular version of the Bourne shell. On manyUNIX systems, /bin/sh is a symbolic link to another shell. For instance, on most Linuxsystems, /bin/sh points to bash (the Bourne-Again Shell), and different Linux distributionsuse different versions of bash.

Ø Invoking a program with root privilege with the system function, for instance, can havedifferent results on different Linux systems. Therefore, it’s preferable to use the fork andexec method for creating processes.

Chapter 3 - Processes52

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 52: MSIT 3A

3.8 CREATING USING SYSTEM CALLS – FORK, EXECØ The DOS and Windows API contain the spawn family of functions. These functions take as

an argument the name of a program to run and create a new process instance of thatprogram. Linux doesn’t contain a single function that does all this in one step.

Ø Instead, Linux provides one function, fork, which makes a child process that is an exactcopy of its parent process. Linux provides another set of functions, the exec family, whichcauses a particular process to cease being an instance of one program and to instead becomean instance of another program.

Ø To spawn a new process, we first use fork to make a copy of the current process. Then weuse exec to transform one of these processes into an instance of the program we want tospawn.

3.9 CREATING BY CALLING FORKØ When a program calls fork, a duplicate process, called the child process, is created. The

parent process continues executing the program from the point that fork was called. Thechild process, too, executes the same program from the same place. So how do the twoprocesses differ?

Ø First, the child process is a new process and therefore has a new process ID, distinct from itsparent’s process ID. One way for a program to distinguish whether it’s in the parent processor the child process is to call getpid. However, the fork function provides different returnvalues to the parent and child processes—one process “goes in” to the fork call, and twoprocesses “come out,” with different return values.

Ø The return value in the parent process is the process ID of the child. The return value in thechild process is zero. Because no process ever has a process ID of zero, this makes it easyfor the program whether it is now running as the parent or the child process.

Ø Listing below is an example of using fork to duplicate a program’s process. Note that thefirst block of the if statement is executed only in the parent process, while the else clause isexecuted in the child process.

Ø Listing ( fork.c) Using fork to Duplicate a Program’s Process

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

int main ()

MSIT 3A Linux Internals 53

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 53: MSIT 3A

{

pid_t child_pid;

printf (“the main program process ID is %d\n”, (int) getpid ());

child_pid = fork ();

if (child_pid != 0) {

printf (“this is the parent process, with id %d\n”, (int) getpid ());

printf (“the child’s process ID is %d\n”, (int) child_pid);

}

else

printf (“this is the child process, with id %d\n”, (int) getpid ());

return 0;

}

3.10 CREATING BY USING THE EXEC FAMILYØ The exec functions replace the program running in a process with another program. When

a program calls an exec function, that process immediately ceases executing that programand begins executing a new program from the beginning, assuming that the exec call doesn’tencounter an error.

Ø Within the exec family, there are functions that vary slightly in their capabilities and howthey are called.

Ø Functions that contain the letter p in their names (execvp and execlp) accept a programname and search for a program by that name in the current execution path; functions thatdon’t contain the p must be given the full path of the program to be executed.

Ø Functions that contain the letter v in their names (execv, execvp, and execve) accept theargument list for the new program as a NULL-terminated array of pointers to strings. Functionsthat contain the letter l (execl, execlp, and execle) accept the argument list using the Clanguage varargs mechanism.

Ø Functions that contain the letter e in their names (execve and execle) accept an additionalargument, an array of environment variables. The argument should be a NULL-terminatedarray of pointers to character strings. Each character string should be of the form“VARIABLE=value”.

Chapter 3 - Processes54

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 54: MSIT 3A

Ø Because exec replaces the calling program with another one, it never returns unless anerror occurs.

3.11 CREATING BY USING FORK AND EXEC TOGETHERØ A common pattern to run a subprogram within a program is first to fork the process and then

exec the subprogram. This allows the calling program to continue execution in the parentprocess while the calling program is replaced by the subprogram in the child process.

3.12 PROCESS SCHEDULINGØ Linux schedules the parent and child processes independently; there’s no guarantee of which

one will run first, or how long it will run before Linux interrupts it and lets the other processrun. In particular, none, part, or all of the ls command may run in the child process before theparent completes. Linux promises that each process will run eventually no process will becompletely starved of execution resources.

Ø We may specify that a process is less important and should be given a lower priority byassigning it a higher niceness value. By default, every process has a niceness of zero. (usenice command)

Ø A higher niceness value means that the process is given a lesser execution priority; conversely,a process with a lower (that is, negative) niceness gets more execution time.

Ø To run a program with a nonzero niceness, use the nice command, specifying the nicenessvalue with the -n option. For example, this is how we might invoke the command “sortinput.txt > output.txt”, a long sorting operation, with a reduced priority so that it doesn’tslow down the system too much:

Example: $ nice -n 10 sort input.txt > output.txt

Ø We can use the renice command to change the niceness of a running process from thecommand line. To change the niceness of a running process programmatically, use the nicefunction.

Ø ITS ARGUMENT IS AN INCREMENT VALUE, WHICH IS ADDED TO THENICENESS VALUE OF THE PROCESS THAT CALLS IT. REMEMBER THATA POSITIVE VALUE RAISES THE NICENESS VALUE AND THUS REDUCESTHE PROCESS’S EXECUTION PRIORITY.

MSIT 3A Linux Internals 55

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 55: MSIT 3A

Ø Note that only a process with root privilege can run a process with a negative niceness valueor reduce the niceness value of a running process. This means that we may specify negativevalues to the nice and renice commands only when logged in as root, and only a processrunning as root can pass a negative value to the nice function. This prevents ordinary usersfrom grabbing execution priority away from others using the system.

3.13 SIGNALSØ Signals are mechanisms for communicating with and manipulating processes in Linux. The

topic of signals is a large one; here we discuss some of the most important signals andtechniques that are used for controlling processes.

Ø A signal is a special message sent to a process. Signals are asynchronous; when a processreceives a signal, it processes the signal immediately, without finishing the current function oreven the current line of code. There are several dozen different signals, each with a differentmeaning.

Ø Each signal type is specified by its signal number, but in programs, we usually refer to asignal by its name. In Linux, these are defined in /usr/include/bits/signum.h. (We shouldn’tinclude this header file directly in our programs; instead, use <signal.h>.)

Ø When a process receives a signal, it may do one of several things, depending on the signal’sdisposition (address space). For each signal, there is a default disposition, which determineswhat happens to the process if the program does not specify some other behavior.

Ø For most signal types, a program may specify some other behavior—either to ignore thesignal or to call a special signal-handler function to respond to the signal. If a signal handleris used, the currently executing program is paused, the signal handler is executed from otheraddress space. When the signal handler returns, the program resumes.

Ø The Linux system sends signals to processes in response to specific conditions. For instance,SIGBUS (bus error), SIGSEGV (segmentation violation), and SIGFPE (floating pointexception) may be sent to a process that attempts to perform an illegal operation.

Ø The default disposition [action] for these signals it to terminate the process and produce acore file.

Ø A process may also send a signal to another process. One common use of this mechanism isto end another process by sending it a SIGTERM or SIGKILL signal.

Ø Another common use is to send a command to a running program. Two “userdefined” signalsare reserved for this purpose: SIGUSR1 and SIGUSR2. The SIGHUP signal is sometimesused for this purpose as well, commonly to wake up an idle program or cause a program toreread its configuration files.

Chapter 3 - Processes56

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 56: MSIT 3A

Ø The sigaction function can be used to set a signal disposition. The first parameter is the signalnumber. The next two parameters are pointers to sigaction structures; the first of thesecontains the desired disposition for that signal number, while the second receives the previousdisposition. The most important field in the first or second sigaction structure is sa_handler.It can take one of three values:

Ø SIG_DFL, which specifies the default disposition for the signal.

Ø SIG_IGN, which specifies that the signal should be ignored.

Ø A pointer to a signal-handler function. The function should take one parameter, the signalnumber, and return void.

Ø Because signals are asynchronous, the main program may be in a very fragile state when asignal is processed and thus while a signal handler function executes. Therefore, we shouldavoid performing any I/O operations or calling most library and system functions from signalhandlers.

Ø A signal handler should perform the minimum work necessary to respond to the signal, andthen return control to the main program (or terminate the program). In most cases, thisconsists simply of recording the fact that a signal occurred. The main program then checksperiodically whether a signal has occurred and reacts accordingly. It is possible for a signalhandler to be interrupted by the delivery of another signal. While this may sound like a rareoccurrence, if it does occur, it will be very difficult to diagnose and debug the problem.Therefore, we should be very careful about what our program does in a signal handler.

Ø Even assigning a value to a global variable can be dangerous because the assignment mayactually be carried out in two or more machine instructions, and a second signal may occurbetween them, leaving the variable in a corrupted state. If we use a global variable to flag asignal from a signal-handler function, it should be of the special type sig_atomic_t.

Ø Linux guarantees that assignments to variables of this type are performed in a single instructionand therefore cannot be interrupted midway. In Linux, sig_atomic_t is an ordinary int; infact, assignments to integer types the size of int or smaller, or to pointers, are atomic. If wewant to write a program that’s portable to any standard UNIX system, though, use sig_atomic_tfor these global variables.

3.14 SOME LINUX DAEMONSØ Daemons are “resident” programs that periodically wake up, check our system and may

perform certain functions. They do not take any input and don’t normally produce any output.

Ø Some daemons normally start when system boots up. They are long running processes,having high [long] life. They do good jobs related to system and users on the system. Rarelythey harm also.

MSIT 3A Linux Internals 57

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 57: MSIT 3A

Ø Our Linux system is likely set to run quite a number of daemons. Most of them can be(dis)selected by running the program ntsysv (RedHat) as root and checking the appropriatebox.

Ø The short description of each daemon is available under netsysv by pressing <F1>. If thedaemon we need is not listed in ntsysv, we need to insert our RedHat installation CD andinstall the appropriate package.

Ø The alternative to ntsysv may be tksysv (type as root, in X terminal), Which is perhapsmore flexible, but way more complicated (it lets us set up the list of daemons to run in eachrunlevel). Another, simpler and even more powerful flexible difficult to use tool is /sbin/chkconfig.

3.15 POPULAR DAEMONSØ Here is a short list of popular daemons with a brief description:

v anacron - checks ‘cron’ jobs that were left out due to down time and executes them.Useful if we have cron jobs scheduled but don’t run our machine all the time—anacronwill detect that during bootup.

v arpwatch - keeps watch for ethernet/ip address pairings.

v autofs - control the operation of automount daemons (competition to amd).

v bootparamd - server process that provides information to diskless clients necessary forbooting.

v crond - automatic task scheduler. Manages the execution of tasks that are executed atregular but infrequent intervals, such as rotating log files, cleaning up /tmp directories,etc.

v cupsd - the Common UNIX Printing System (CUPS) daemon. CUPS is an advancedprinter spooling system which allows setting of printer options and automatic availabilityof a printer configured on one server in the whole network. The default printing systemof Linux Mandrake.

v dhcpd - implements the Dynamic Host Configuration Protocol (DHCP) and the InternetBootstrap Protocol (BOOTP).

v gpm - useful mouse server for applications running on the Linux text console.

v httpd - daemon for the Apache webserver.

v inetd - listens for service requests on network connections, particularly dial-in services.

Chapter 3 - Processes58

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 58: MSIT 3A

This daemon can automatically load and unload other daemons (ftpd, telnetd, etc.), therebyeconomizing on system resources. Newer systems use xinetd instead.

v kudzu - detects and configures new or changed hardware during boot.

v linuxconf - the linuxconf configuration tool. The automated part is run if we want linuxconfto perform various tasks at boottime to maintain the system configuration.

v lpd - printing daemon.

v named - the Internet Domain Name Server (DNS) daemon.

v netfsd - network filesystem mounter. Used for mounting nfs, smb and ncp shares onboot.

v networkd -activates all network interfaces at boot time by calling scripts in /etc/sysconfignetwork-scripts.

v nfsd - used for exporting nfs shares when requested by remote systems.

v portmap - needed for Remote Procedure Calls. Most likely, we need it for runningnetwork.

v routed - daemon that manages routing tables.

v rstatd - kernel statistics server.

v rusersd, rwalld - identification of users and “wall” messaging services for remote users.

v rwhod - server which maintains the database used by the rwho(1) and ruptime(1)programs. Its operation depends on the ability to broadcast messages on a network.

v sendmaild - mail transfer agent. This is the agent that comes with Red Hat.

v smbd - the SAMBA (or smb) daemon, a network connectivity services to MS Windowscomputers on our network (hard drive sharing, printers, etc).

v squid - An http proxy with caching. Proxies relay requests from clients to the outsideworld, and return the results. We would use this particular proxy if we wanted to use ourlinux computer as a gateway to the Internet for other computer on our network. Another(and probably safer at home) way to do it, is to set up masquarading.

v syslogd - manages system activity logging. The configuration file is /etc/syslog.conf.

v smtpd - Simple Mail Transfer Protocol, designed for the exchange of electronic mailmessages. Several daemons that support SMTP are available, including sendmail, smtpd,rsmtpd, qmail, zmail, etc.

v ypbind - NIS binder. Needed if computer is part of Network Information Service domain.

MSIT 3A Linux Internals 59

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 59: MSIT 3A

3.16 ZOMBIE PROCESSv If a child process terminates while its parent is calling a wait function, the child process

vanishes and its termination status is passed to its parent via the wait call.

v But what happens when a child process terminates and the parent is not calling wait? Doesit simply vanish? No, because then information about its termination—such as whether itexited normally and, if so, what its exit status is—would be lost. Instead, when a childprocess terminates, is becomes a zombie process.

v A zombie process is a process that has terminated but has not been cleaned up yet. It is theresponsibility of the parent process to clean up its zombie children.

v The wait functions do this, too, so it’s not necessary to track whether our child process is stillexecuting before waiting for it. Suppose, for instance, that a program forks a child process,performs some other computations, and then calls wait. If the child process has not terminatedat that point, the parent process will block in the wait call until the child process finishes.

v If the child process finishes before the parent process calls wait, the child process becomesa zombie. When the parent process calls wait, the zombie child’s termination status is extracted,the child process is deleted, and the wait call returns immediately.

v Orphan process is a parent less child.

v What happens if the parent does not clean up its children? They stay around in the system, aszombie processes. The program in Listing below forks a child process, which terminatesimmediately and then goes to sleep for a minute, without ever cleaning up the child process.

v Listing (zombie.c) Making a Zombie Process

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

int main ()

{

pid_t child_pid;

/* Create a child process. */

child_pid = fork ();

if (child_pid > 0) {

/* This is the parent process. Sleep for a minute. */

sleep (60);

Chapter 3 - Processes60

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 60: MSIT 3A

}

else {

/* This is the child process. Exit immediately. */

exit (0);

}

return 0;

}

Ø Try compiling this file to an executable named make-zombie. Run it, and while it’s still running,list the processes on the system by invoking the following command in another window:

$ ps -e -o pid,ppid,stat,cmd

Ø This lists the process ID, parent process ID, process status, and process command line.Observe that, in addition to the parent make-zombie process, there is another make-zombieprocess listed. It’s the child process; note that its parent process ID is the process ID of themain make-zombie process.

Ø The child process is marked as <defunct>, and its status code is Z, for zombie.

Ø What happens when the main make-zombie program ends when the parent process exits,without ever calling wait? Does the zombie process stay around? No—try running ps again,and note that both of the make-zombie processes are gone.

Ø When a program exits, its children are inherited by a special process, the init program, whichalways runs with process ID of 1 (it’s the first process started when Linux boots).The initprocess automatically cleans up any zombie child processes that it inherits.

3.17 THREADSØ Threads, like processes, are a mechanism to allow a program to do more than one thing at a

time. As with processes, threads appear to run concurrently; the Linux kernel schedulesthem asynchronously, interrupting each thread from time to time to give others a chance toexecute.

Ø Conceptually, a thread exists within a process. Threads are a finer-grained unit of executionthan processes. When we invoke a program, Linux creates a new process and in that processcreates a single thread, which runs the program sequentially. That thread can create additionalthreads; all these threads run the same program in the same process, but each thread may beexecuting a different part of the program at any given time.

MSIT 3A Linux Internals 61

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 61: MSIT 3A

Ø We’ve seen how a program can fork a child process. The child process is initially running itsparent’s program, with its parent’s virtual memory, file descriptors, and so on copied. Thechild process can modify its memory, close file descriptors, and the like without affecting itsparent, and vice versa.

Ø When a program creates another thread, though, nothing is copied. The creating and thecreated thread share the same memory space, file descriptors, and other system resourcesas the original. If one thread changes the value of a variable, for instance, the other threadsubsequently will see the modified value.

Ø Similarly, if one thread closes a file descriptor, other threads may not read from or write tothat file descriptor. Because a process and all its threads can be executing only one programat a time, if any thread inside a process calls one of the exec functions, all the other threadsare ended (the new program may, of course, create new threads).

3.18 PROCESSES VS. THREADSØ For some programs that benefit from concurrency, the decision whether to use processes or

threads can be difficult. Here are some guidelines to help us decide which concurrencymodel best suits our program:

1. All threads in a program must run the same executable. A child process, on the otherhand, may run a different executable by calling an exec function.

2. An errant thread can harm other threads in the same process because threads share thesame virtual memory space and other resources. For instance, a wild memory writethrough an un initialized pointer in one thread can corrupt memory visible to anotherthread.

An errant process, on the other hand, cannot do so because each process has a copy ofthe program’s memory space.

3. Copying memory for a new process adds an additional performance overhead relative tocreating a new thread. However, the copy is performed only when the memory is changed,so the penalty is minimal if the child process only reads memory.

4. Threads should be used for programs that need fine-grained parallelism. For example, ifa problem can be broken into multiple, nearly identical tasks, threads may be a goodchoice. Processes should be used for programs that need coarser parallelism.

5. Sharing data among threads is trivial because threads share the same memory.

Chapter 3 - Processes62

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 62: MSIT 3A

3.19 SUMMARYØ Process defined as:

“A process is program (command given by user) to perform specific Job. In Linuxwhen you start process, it gives a number to process (called PID or process-id), PIDstarts from 0 to 65535.”

Ø Process & PID defined as:

“An instance of running command is called process and the number printed by shell iscalled process-id (PID), this PID can be use to refer specific running process.”

Ø TOOLS FOR WORKING WITH PROCESSES

v accton - Turns process accounting on and off. Uses the file /var/log/pacct. To turn it ontype “accton /var/log/pacct”. Use the command with no arguments to turn it off.

v kill - Kill a process by number

v killall - Send a signal to a process by name

v lastcomm (1) - Display information about previous commands in reverse order. Worksonly if process accounting is on.

v nice - Set process priority of new processes.

v ps(1) - Used to report the status of one or more processes.

v pstree(1) - Display the tree of running processes.

v renice(8) - Can be used to change the process priority of a currently running process.

v sa(8) - Generates a summary of information about users’ processes that are stored in the/ var/log/pacct file.

v skill - Report process status.

v snice - Report process status.

v top - Displays the processes that are using the most CPU resources.

MSIT 3A Linux Internals 63

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 63: MSIT 3A

3.20 CHECK YOUR PROGRESS

I. Exercisesv You are working on your Linux workstation (like sending mails, typing letter), while doing this

work you have started to play MP3 files on your workstation. Regarding this situation, answerthe following question:

1) Is it example of Multitasking?

2) How you will find out the both running process (MP3 Playing & Letter typing)?

3) “Currently only two Process are running in your Linux / PC environment”, Is it True orFalse?, And how you will verify this?

4) You don’t want to listen music (MP3 Files) but want to continue with other work on PC,you will take any of the following action:

1. Turn off Speakers

2. Turn off Computer / Shutdown Linux Os

3. Kill the MP3 playing process

4. None of the above

II. Choose the correct answer1. An example of system call is ______.

a. fork

b. exec

c. wait

d. all of the above.

2. process is a ________ entity.

a. passive

b. dynamic

c. static

d. none of the above.

Chapter 3 - Processes64

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 64: MSIT 3A

3. To run a command in the background, add the “&” character ________of the commandline.

a. At the end

b. At the beginning

c. In the middle

d. Any where

4. We can kill a process by typing ______ and the PID number right afterwards.

a. pid

b. kill

c. signal

d. none of the above

5. Common techniques used for creating a new process is using ______.

a. system().

b. fork()

c. fork(), exec() and wait()

d. All of the above

6. ________ command is used to set priority for the process.

a. more

b. less

c. nice

d. all of the above.

7. _____ are long running processes, having high [long] life.

a. Daemons

b. Threads

c. Zombie

d. Orphan

MSIT 3A Linux Internals 65

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 65: MSIT 3A

III. Say True or False1. Each signal type is specified by its signal number. True / False

2. Threads, like processes, are a mechanism to allow a program to domore than one thing at a time True / False

3. Process IDs are 16-bit numbers that are assigned sequentially by Linuxas new processes are created. True / False

4. A signal is program (command given by user) to perform specific Job.

5. pstree() - Display the tree of running processes. True / False

IV. Essay type questions1. What is meant by process ? Explain it’s states briefly.

2. Explain how a process can be created.

3. What is meant by background processing ? illustrate with example.

4. Differentiate a process and thread in detail.

5. What is a daemon? Describe the most popular daemons with their functions.

6. Describe the output formats of ps command with respect to performance analysis.

7. Elucidate the techniques of creating the processes with examples.

8. Write a note on zombie, thread, daemon and Orphan.

9. Explain the different types of Linux processes.

V. Further readings and other activities1. Get more information using man or info or any help command for

init, getty, daemon, telnetd, SIGQUIT, SIGABRT, ps, top, nice.

2. Work on processes by executing small programs.:

Following table lists most commonly used command(s) with process:

Chapter 3 - Processes66

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 66: MSIT 3A

* To run some of this command you need to be root or equivalent user.

3. Books for Reference

Ø Title: Linux internals

MSIT 3A Linux Internals 67

For this purpose Use this Command Examples*

To see currently running process ps $ ps

To stop any process byPID i.e. to kill process kill {PID} $ kill 1012

To stop processes by namei.e. to kill process killall {Process-name} $ killall httpd

To get information aboutall running process ps –ag $ ps –ag

To stop all process exceptyour shell kill 0 $ kill 0

For background processing(With &, use to put particularcommand and program inbackground) linux-command & $ ls / -R | wc -l &

To display the owner of theprocesses along with theprocesses ps aux $ ps aux

To see if a particular For e.g. you want toprocess is running or not. see server process isFor this purpose you have to runningor not then giveuse ps command in combination ps ax | grep process- commandwith the grep command U-want-to see $ ps ax | grep httpd

To see currently running $ topprocesses and otherinformation like memory and top Note that to exit fromCPU usage with real time top command press q.updates.

To display a tree of processes pstree $ pstree

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 67: MSIT 3A

Auihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.pandurangarao.i8.com/doc/linux/linuxbook.html

http://www. geocities.com/raomvp/doc/linux/linuxbook.html

A complete reference for you to get more information.

You can also extract solutions for exercises.

Ø Title: Linux in a Nutshell - a good overview of all the most common Linux commands,process including a comprehensive section on the bash shell.

VI. Solutions

I. Exercises 1) Is it example of Multitasking?

Ans.: Yes, since we are running two process simultaneously.

2) How you will find out the both running process (MP3 Playing & Letter typing)?Ans.: Try $ ps -aux or $ ps -ax | grep process-you-want-to-search

3) “Currently only two Process are running in your Linux/PC environment”, Is it True or False?,And how you will verify this?Ans.: No its not true, when you start Linux Os, various process start in background for differentpurpose. To verify this simply use top or ps -aux command.

4) You don’t want to listen music (MP3 Files) but want to continue with other work on PC, you willtake any of the following action:1. Turn off Speakers2. Turn off Computer / Shutdown Linux Os3. Kill the MP3 playing process4. None of the above

Ans.: Use action no. 3 i.e. kill the MP3 process.

Tip: First find the PID of MP3 playing process by issuing command:

$ ps -ax | grep mp3-process-name

Then in the first column you will get PID of process. Kill this PID to end the process as: $ kill PID

Or you can try killall command to kill process by name as follows:

$ killall mp3-process-name

Chapter 3 - Processes68

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 68: MSIT 3A

MSIT 3A Linux Internals 69

II. Choose appropriate answer1.d 2.b 3.a 4.b 5.d 6.c 7.a

III. Say True or False 1. True 2. True 3. True 4. False 5. True

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 69: MSIT 3A

Chapter 4 - Shell Programming70

Chapter 4

Shell Programming

4.0 INTRODUCTION AND OBJECTIVES

A shell script is a series of shell commands, similar to the ones given above, contained in a file,which can be given to the bash program to be executed in sequence. Technically, it is a programwith “bash” as the language.

There are several shells available on the Linux system (if we installed them): bash (“Bourne Again”shell), sh (Bourne shell, standard on many UNIX systems), csh (C shell, with a syntax akin to the “c”programming language, available on most UNIX systems), pdksh (public domain Korn shell), tcsh (tiny Cshell, often used on small systems), sash (stand-alone shell, could be used when libraries are not available),ash, zsh, and perhaps a couple more.

ObjectivesAt the end of this unit, You would be able to

ð Understand the analogy of shell programming

ð Creation of a shell script

ð Meta characters

ð Positional Parameters and Shell Variables

ð Built-in shell commands and variables

ð Iteration, control and if statements

ð Shell operators

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 70: MSIT 3A

ð The test Command

ð An example script

ð Environment Variables

4.1 CREATING A SHELL SCRIPTØ We can use any text editor to create the shell script - simply choose one, that we are

comfortable with. If we are using KDE, We can use the Advanced Editor (kate or kwrite),or kedit. Do not use a word processing program - these are not text editors, and insertadditional formatting information into the text. If, however, we know how to use our wordprocessor to save plain-text file, go ahead and use it.

Ø Start with a new file firstshellscript.sh, and type the following lines.

Example:$ vi firstshellscipt.sh#!/bin/bashecho “I am about to list the files present in home directory”# here is the actual listing:ls $HOME # HOME = /rao/laptopecho “Done!”

Ø The first line has a special meaning. It tells the current shell which program should be usedto interpret this file. Here, we have given the filename of the bash program. This is so that,if this script is invoked from within a different shell, or from a file-management program suchas Konqueror and Nautilus, it will still know that this script requires the bash shell to run it.

Ø The second line is our first command. We use the “echo” command to display a simple lineof information.

Ø The third line is a comment. Bash simply ignores it, but it can be useful to a person readingthe program in the future to understand what the code is trying to do. While comments arenot very useful in such a short, simple script, they are vital in longer and more cryptic ones.

Ø This is followed by two more commands - the “ls” command which takes the directory nameas a parameter, and finally another “echo” to display our final declaration of triumph!

Ø When we save this file, it shows up as an ordinary file, which cannot be executed. In orderto run it, we must make it executable. To do this, we use the “chmod” command. In thefollowing example, we have used “firstshellscript.sh” as the script name - we should changethat to whichever name we used.$ chmod u+x firstshellscript.sh

MSIT 3A Linux Internals 71

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 71: MSIT 3A

Ø That’s it! We can now execute the new script. To do this, enter the following command,again replacing “firstshellscript.sh” with the name we used if different.

rao@laptop $ ./firstshellscript.shI am about to list the home directoryKDesktop firstshellscript.sh public_html snapshot1.png usr-listing.txtDone!

Ø Note the “./” at the beginning of the file - this is actually a directory name (a single periodmeans the current directory). We can avoid this by placing the new script, and any others wecreate, in a directory within the PATH environment variable. Then we can enter the commandfrom wherever we are.

4.2 META CHARACTERSØ The following table provides a list of characters or combination characters called as meta

characters [wildcards]. They have special predefined meaning to the shell. By using one ormore special symbols, the shell will find those files, which match a pattern, and place them onthe command line instead of the pattern itself.

v Meaning of some special characters.

Character Meaning

$ Indicates the beginning of a shell variable name. For example, $var will lookfor a shell variable named var.

| Pipes standard output to next command.

# Start a comment.

& Executes a process in the background.

? Matches one character.

* Matches none or more characters.

$# Number of arguments passed to a shell script.

$* Arguments passed to a shell script.

$? Returns code from the previous executed command.

$$ Process identification number.

Chapter 4 - Shell Programming72

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 72: MSIT 3A

> Output redirection operator.

< Input redirection operator.

‘ (backquote) Command substitution.

>> Output redirection operator (to append to a file).

[ ] Lists a range of characters. [a-z] means all characters a through z. [a,z]means characters a or z.

. filename Executes the file filename

: Directory name separator in the path.

4.3 POSITIONAL PARAMETERS AND SHELL VARIABLESØ The shell has knowledge of a special kind of variable called a positional parameter. Positional

parameters are used to refer to the parameters that were passed to a shell program on thecommand line or a shell function by the shell script that invoked the function. When we runa shell program that requires or supports a number of command-line options, each of theseoptions is stored into a positional parameter. The first parameter is stored into a variablenamed 1, the second parameter is stored into a variable named 2, and so forth. The shellreserves these variable names so that we can’t use them as variables we define. To accessthe values stored in these variables, we must precede the variable name with a dollar sign ($)just as we do with variables we define.

Ø The following shell program expects to be invoked with two parameters. The program takesthe two parameters and prints the second parameter that was typed on the command linefirst and the first parameter that was typed on the command line second.

$ vi reverse.sh

#program reverse.sh, prints the command line parameters out in reverse #order

echo “$2” “$1”

If we invoked this program by entering

$ sh reverse.sh hello there

the program would return the following output:

there hello

MSIT 3A Linux Internals 73

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 73: MSIT 3A

4.4 BUILT-IN SHELL COMMANDS AND VARIABLESØ Several other built-in shell commands and variables are important to know about when we

are doing a lot of shell programming. Table below lists these commands and variables andgives a brief description of what each is used for.

v BUILT-IN SHELL COMMANDS.

Command Description

alias Defines or lists a command alias

bg Switches a job to background execution

break Breaks out of a loop

breaksw Exits from a switch statement

case Begins a case in switch

cd Changes directory

chdir Changes directory

continue Begins the next loop iteration immediately

default Specifies the default case in switch

dirs Lists the directory stack

echo Echoes arguments to standard output

eval Rescans a line for substitutions

exec Replaces the current process with a new process

exit Exits from the current shell

fg Switches a job to foreground execution

foreach Specifies a looping control statement

glob Echoes arguments to standard output

goto Alters the order of command execution

hashstat Prints hash table statistics

history Lists the command history

if Specifies conditional execution

jobs Lists active jobs

kill Signals a process

Chapter 4 - Shell Programming74

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 74: MSIT 3A

limit Respecifies maximum resource limits

login Invokes the system logon procedure

logout Exits from a logon shell

newgrp Changes our Group ID

nice Controls background process dispatch priority

nohup Prevents termination on logout

notify Requests notification of background job status changes

onintr Processes an interrupt within a shell script

popd Returns to a previous directory

pushd Changes directory with pushdown stack

rehash Rehashes the directory search path

repeat Executes a command repeatedly

set Displays or changes a shell variable

setenv Sets environment variable

shift Shifts parameters

source Interprets a script in the current shell

stop Stops a background job

suspend Stops the current shell

switch Specifies conditional execution

time Times a command

umask Displays or sets the process file-creation mask

unalias Deletes a command alias

unhash Disables use of the hash table

unlimit Cancels a previous limit command

unset Deletes shell variables

unsetenv Deletes environment variables

wait Waits for background jobs to finish

while Specifies a looping control

%job Specifies foreground execution

@ Specifies expression evaluation

MSIT 3A Linux Internals 75

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 75: MSIT 3A

v Built-in shell variables

Variable Use

$# Stores the number of command-line arguments that were passed to the shell program.

$? Stores the exit value of the last command that was executed.

$0 Stores the first word of the entered command (the name of the shell program).

$* Stores all the arguments that were entered on the command line ($1 $2 ...).

“$@” Stores all the arguments that were entered on the command line, individually quoted(“$1” “$2” ...).

4.5 ITERATION, CONTROL AND IF STATEMENTSØ if - Used to execute one or more statements on a condition. An example:

if [ ! -d /mnt ] # be sure the directory /mnt existsthenmkdir /mntfi

Ø case - Used to execute specific commands based on the value of a variable. An example:

case $NUM1) echo The number is 1 ;;2) echo The number is 2 ;;*) echo The number is not 1 or 2 ;;esac

Ø for - Used to loop for all cases of a condition. In the example below, it is used to copy all filesfound in /mnt/floppy to the /etc directory. The lines were numbered for reference withdescriptions:

1 The for loop statement will loop until all files have been found.

2 A test to be sure the file is a normal file and not a directory.

Chapter 4 - Shell Programming76

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 76: MSIT 3A

3 A comment line.

4 This line extracts the name of the file from its full path pointed to by the variable $i andputs it in the variable $filename. The method used here is called parameter expansionand is documented in the bash man page. For more information on parameter expansionread the “Linux Programmer’s Guide”.

5 This line sends a statement to the standard output, telling what file is being copied.

6 This line performs the copy command using the -p option to preserve file attributes. Note:Much ability to perform script programming is couched in the ability to know and use thevarious commands, programs and tools available in Linux rather than a strict understandingof syntax. This is obvious to anyone who reads the system startup script files in /etc/rc.dand associated directories.

7 This line ends the if statement.

8 This line ends the for statement.

1. for i in /mnt/floppy/*; do

2. if [ -f $i ]; then3. # if the file is there4. filename=${i#/mnt/floppy/}5. echo copying $i to /etc/$filename6. cp -p $i /etc/$filename7. fi8. done

Ø until - Cycles through a loop until some condition is met. The syntax for the command isshown below:

until [ expression ]dostatementsdone

Ø while - Cycles through a loop while some condition is met. The below example will cyclethrough a loop forever:

while [ 1 ]dostatement(s)done

MSIT 3A Linux Internals 77

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 77: MSIT 3A

4.6 SHELL OPERATORSFor Mathematics, use following operator in Shell Script:NOTE: == is equal, ! = is not equal.

For string Comparisons use:

Chapter 4 - Shell Programming78

Mathematical Operator in Shell Script

Meaning

Normal Arithmetical/ Mathematical

Statements

But in Shell

For test

statement with if command

For [ expr ] statement with if

command

-eq is equal to 5 == 6 if test 5 - eq 6 if [ 5 -eq 6 ] -ne is not equal to 5 != 6 if test 5 - ne 6 if [ 5 -ne 6 ] -lt is less than 5 < 6 if test 5 - lt 6 if [ 5 -lt 6 ]

-le is less than or equal to 5 <= 6 if test 5 - le 6 if [ 5 -le 6 ]

-gt is greater than 5 > 6 if test 5 - gt 6 if [ 5 -gt 6 ]

-ge is greater than or equal to 5 >= 6 if test 5 - ge 6 if [ 5 -ge 6 ]

Operator Meaning string1 = string2 string1 is equal to string2 string1 != string2 string1 is NOT equal to string2 string1 string1 is NOT NULL or not defined -n string1 string1 is NOT NULL and does exist -z string1 string1 is NULL and does exist

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 78: MSIT 3A

Shell also test for file and directory types:

Logical Operators :

LOGICAL OPERATORS ARE USED TO COMBINE TWO OR MORE CONDITION AT ATIME

4.7 THE TEST COMMANDØ In bash and sh, a command called test is used to evaluate conditional expressions. We would

typically use the test command to evaluate a condition that is used in a conditional statementor to evaluate the entrance or exit criteria for an iteration statement. The test command hasthe following syntax:

test expressionor[ expression ]

Ø Several built-in operators can be used with the test command. These operators can beclassified into four groups: integer operators, string operators, file operators, and logicaloperators.

Ø The shell integer operators perform similar functions to the string operators except that theyact on integer arguments. Table below lists the test command’s integer operators.

MSIT 3A Linux Internals 79

Test Meaning -s file Non empty file -f file Is File exist or normal file and not a directory -d dir Is Directory exist and not a file -w file Is writeable file -r file Is read -only file -x file Is file is executable

Operator Meaning ! expression Logical NOT expression1 -a expression2 Logical AND expression1 -o expression2 Logical OR

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 79: MSIT 3A

THE TEST COMMAND’S INTEGER OPERATORS :

Operator Meaning

int1 –eq int2 Returns True if int1 is equal to int2.

int1 –ge int2 Returns True if int1 is greater than or equal to int2.

int1 –gt int2 Returns True if int1 is greater than int2.

int1 –le int2 Returns True if int1 is less than or equal to int2.

int1 –lt int2 Returns True if int1 is less than int2.

int1 –ne int2 Returns True if int1 is not equal to int2.

Ø The string operators are used to evaluate string expressions. Table lists the string operatorsthat are supported by the three shell programming languages.

THE TEST COMMAND’S STRING OPERATORS:

Operator Meaning

str1 = str2 Returns True if str1 is identical to str2.

str1 != str2 Returns True if str1 is not identical to str2.

str Returns True if str is not null.

-n str Returns True if the length of str is greater than zero.

-z str Returns True if the length of str is equal to zero.

Ø The test command’s file operators are used to perform functions such as checking to see ifa file exists and checking to see what kind of file is passed as an argument to the testcommand. Table below lists the test command’s file operators.

The test command’s file operators:

Operator Meaning-d filename Returns True if file, filename is a directory.-f filename Returns True if file, filename is an ordinary file.-r filename Returns True if file, filename can be read by the process.-s filename Returns True if file, filename has a nonzero length.-w filename Returns True if file, filename can be written by the process.-x filename Returns True if file, filename is executable.

Chapter 4 - Shell Programming80

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 80: MSIT 3A

Ø The test command’s logical operators are used to combine two or more of the integer, string,or file operators or to negate a single integer, string, or file operator. Table below lists the testcommand’s logical operators.

THE TEST COMMAND’S LOGICAL OPERATORS:

Command Meaning

! expr Returns True if expr is not true.

expr1 -a expr2 Returns True if expr1 and expr2 are true.

expr1 -o expr2 Returns True if expr1 or expr2 is true.

4.8 AN EXAMPLE SCRIPTØ The file below is an example file, which demonstrates some of the testing as talked above along

with several looping and control statements.

#! /bin/bash

# Use the bash shell to run the script

# This is an example file to take entries from the user

# entries Version 1.0 jan 29, 2005

DONE=no

ENTRIES=”hello bye ls 1"

while [ $DONE = no ]

do

echo Valid entries are: $ENTRIES

read ENTRY # Read the variable ENTRY from the user

case $ENTRY in

1)pwd;;

hello)echo How are you?;;

bye)

MSIT 3A Linux Internals 81

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 81: MSIT 3A

echo exiting...DONE=yes;;

ls)ls -al |more;;

*)echo $ENTRY is an unrecognized command.;;

esacdone

4.9 ENVIRONMENT VARIABLESØ Environment variables are variables that the shell or any other program can access to get

information unique to a specific user. Any program can use environment variables. The vieditor, for example, checks the variable EXINIT for any standard options we want to setevery time we run vi.

Ø Several environment variables are created and used by the Bourne shell.

Ø We can type “$ env or $ set” to see a listing of all current environment variables.

Ø The command used to add or modify environment variables is the export built-in commandprovided by the bash shell.

Ø HOME: This variable is initialized when the interactive shell is executed by the login program.It contains the value of the user’s home directory. If the cd command is executed withoutany arguments, the effect is cd $HOME.

Ø IFS: This variable sets characters to be internal field separators, or the characters that separatewords on a command line. By default, the internal field separators are the space, tab, andnewline characters. Setting the IFS adds separators, but space, tab, and the newline characteralways separate fields.

Ø MAIL: This variable specifies the complete pathname of the user’s mailbox file.

Ø MAILCHECK: This variable specifies in seconds how often the mailbox should be checkedfor incoming mail.

Ø MAILPATH: This variable is a colon-separated list of mailbox files to be checked.

Chapter 4 - Shell Programming82

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 82: MSIT 3A

Ø PATH: This variable, usually set in our .profile, contains a list of directories that are searchedfor executables. If an executable, Which is any utility, program, or shell program, is not in thePATH variable, it can only be executed by giving the full pathname of the executable file.The directories are searched in the order in which they appear in the PATH variable.

Ø PS1: The value of the interactive shell prompt. The default value in the Bourne Shell is $.[set $ ps1=” [pwd] “ > and then invoke $ echo $PS1 ]

Ø PS2: The value of the secondary shell prompt. The default value is >.

Ø TERM: This variable is not automatically created on all UNIX systems but is used by somany programs that it is considered a standard environment variable. TERM usually containsthe type of terminal that we are using, such as ansi or vt100.

Ø SHELL: The current shell program that is being executed. Default is /bin/bash

Ø USER - The name of the current user.

4.10 SUMMARYØ A shell script is simply a text file containing shell commands. What makes shell scripts

especially handy is the capability to execute the commands in the file simply by typing thefile’s name as if it were a command.

Ø Generally, we’ll want to write a shell script when we recognize either of two situations:

v We find ourselves repeating a lengthy series of commands over and over to accomplishone general task. Any time we need to accomplish a task on a fairly frequent basis (daily,weekly, or maybe several times a day), and the task requires more than one UNIXcommand, the task is a good candidate for packaging in a shell script.

v A repeatable procedure needs to be established for a formal activity. Printing a weeklycustomer invoicing report, for example, might require a complex procedure—extractingbilling information from a master file, computing the invoice data, setting up the printer,and actually generating the print file.

Ø When variables are used they are referred to with the $ symbol in front of them. There areseveral useful variables available in the shell program. Here are a few:

ð $$ = The PID number of the process executing the shell.

ð $? = Exit status variable.

ð $0 = The name of the command we used to call a program.

ð $1 = The first argument on the command line.

MSIT 3A Linux Internals 83

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 83: MSIT 3A

ð $2 = The second argument on the command line.

ð $n = The nth argument on the command line.

ð $* = All the arguments on the command line.

ð $# The number of command line arguments.

Ø The “shift” command can be used to shift command line arguments to the left, ie $1 becomesthe value of $2, $3 shifts into $2, etc. The command, “shift 2” will shift 2 places meaning thenew value of $1 will be the old value of $3 and so forth.

4.11 CHECK YOUR PROGRESS

I. ExercisesØ Work on the following list of shell programming concepts.

1) Write a simple shell script program for displaying current date, all logged-in users andprocess status using switch-case construct.

2) Write a shell script program to count the number of vowels, consonants and digits in agiven text.

3) Write a shell script program to check whether a given string is palindrome or not.

4) Explain all the test operators related to files with a example.

II. Choose the correct answer1) Shell is a __________.

a) Interpreter

b) Compiler

c) Assembler

d) Linker

2) Shell scripts are not useful when applications are__________

a) complex

b) portable

c) secured

Chapter 4 - Shell Programming84

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 84: MSIT 3A

d) all of the above

3) All LINUX systems have the following _________

a) stdin

b) stdout

c) stderr

d) all of the above

4) < redirects the _________

a) stdin

b) stdout

c) stderr

d) none of the above

5) chmod 777 scriptname gives _________ permission.

a) Read / execute

b) Read / write / execute

c) Read / write

d) Write / execute

6) The symbol used for command separator ____.

a) ; b) ;; c) , d) .

7) Terminator in a case option ___ .

a) ; b) , c) “ d) ;;

8) ________ runs job in background.

a) Sleep 100

b) Sleep 100 &

c) & sleep 100

d) sleep & 100

MSIT 3A Linux Internals 85

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 85: MSIT 3A

9) ____ is the name of the script.

a) $1 b) $2 c) $0 d) none of the above

10) shift command _____________________________________.

a) reassigns the positional parameters, in effect shifting them to the right one notch.

b) reassigns the positional parameters, in effect shifting them to the left one notch.

c) reassigns the positional parameters, in effect shifting them to the both right & left onenotch.

d) None of the above.

11) Pipelines are used to ________ commands.

a) reverse b) connect c) both a) & b) d) none of these

12) _____ is a synonym for test.

a) ] b) [ c) both a) & b) d) none of these

13) [ “$a” –ne “$b” ] is ________________.

a) Arithmetic comparison

b) String comparison

c) Both a) & b)

d) Neither a) nor b)

14) Following are the internal variables _______.

a) $HOME

b) $PATH

c) all of the above

d) none of the above

15) case test line ends with ______.

a) ) b) ( c) )) d) none of the above.

Chapter 4 - Shell Programming86

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 86: MSIT 3A

III. Say True or False1. Exit status 0 results false. True/False

2. Bash an acronym for Bourne-Again Shell. True/False

3. The backquotes around the command illustrate the use of command True/Falsereplacement.

4. Environment variables are variables that the shell or any other programcan access to get information unique to a specific user. True/False

IV. Essay type questions1) What is shell? Why shell programming is required.

2) When shell scripts are n’t useful?

3) Breifly explain the access permissions related to different types of users.

4) Elaborate all the looping control constructs.

5) Explain all the string-related operators.

6) What are meta characters [wildcards]? Give examples.

7) What are positional parameters? Give examples.

8) Elucidate built-in shell commands and variables.

9) Explain the test command with all options.

V. Further readings and other activities1. Get more information using man or info or any help command for

ksh, sh, bash, tcsh, csh, ksh, ls, vi.EX: 1. $ man sh 2. $ apropos shellWork on all of the example explained in the unit. Some exercises also are giventhere itself relating to the particular topic.

2. For further readings you can refer the following books

Ø Title: Linux internals

Auihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.pandurangarao.i8.com/doc/linux/linuxbook.html

http://www.raomvp.bravepages.com/doc/linux/linuxbook.html

MSIT 3A Linux Internals 87

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 87: MSIT 3A

A complete reference for you to get more information.

You can also extract solutions for exercises.

Ø Title: UNIX Shell Programming

Author: Stephen G. Kochan and Patrick H. Wood; Howard Sams;

ISBN 0-672-48448-X; 1990. An excellent introduction to Bourne and Korn shell programmingwith lots of illustrative examples.

Ø Title: Unix Shell Programming

Author: Yashawant Kanitkar

Publication: BPB

VI. SolutionsI. Choose the correct answer

1.a 2.d 3.d 4.a 5.b 6.a 7.a 8.b 9.c 10.b 11.b 12.b 13.a 14.c 15.a

II. Say True or False

1.False 2.True 3.False 4.True

Chapter 4 - Shell Programming88

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 88: MSIT 3A

Chapter 5

File System

5.0 INTRODUCTION AND OBJECTIVES

Linux is inherently multi-user. Your personal settings (and all other personal files) are in your homedirectory which is /home/your_user_login_name. Many settings are kept in files with namesstarting with a dot “.”

LINUX IS CASE-SENSITIVE. Your user login name and password are also case sensitive. Filenamescan be up to 256 characters long and can contain letters, numbers, “.” (dots), “_” (underscores), “-”(dashes), plus some other non-recommended characters.

Files with names starting with “.” are normally not shown by the ls (list) or dir command. Think ofthese “dot” files as “hidden”. Use ls -a (list with the option “all”) to see these files.

“/” is an equivalent to DOS “\” (root directory, meaning the parent of all other directories, or a separatorbetween a directory name and a subdirectory or filename).

Under Linux, all directories appear under a single directory tree (there are no DOS-style drive letters).This means directories and files from all physical devices are merged into this single-view tree.

Under Linux, as in any multiuser operating system, directories and files have an owner and set ofpermissions. You will typically be allowed to write only to your home directory which is /home/your_user_login_name.

ObjectivesAfter completing this section, you will be able to:

ð Understand a typical Linux filesystem

MSIT 3A Linux Internals 89

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 89: MSIT 3A

ð Basic types of files

ð Navigate the file hierarchy

ð Manipulate files and directories

ð Operations on directories

ð Options of inodes

ð Links- hard links and soft links

ð Handle access control

ð Changing access privileges: chmod

ð chmod symbolically and numerically

ð umask masking Privileges

ð Deal with ‘special files’ and links

ð Mounting volumes and filesystems

5.1 FILE SYSTEM OVERVIEWLinux uses ext2 as its native filesystem. It also supports many other types. All data stored on a Linux

system is a file. Ext2 file names can be 1 to 255 characters long. Only / and nul are disallowed. Non-native filesystems have different features. Ext2 sees only two basic types of files: directories and files.

5.2 TYPES OF FILESØ Files come in 8 flavors:

ð Normal Filesð Directoriesð Hard Linksð Symbolic linksð Socketsð Named Pipesð Character Devicesð Block Devices

Chapter 5 - File System90

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 90: MSIT 3A

Ø Normal Files:

These are the files you use the most. They can be either text or binary files; however, theirinternal structure is irrelevant from a System Administrator standpoint. An ls -l on a normalfile will look something like this.

-rw------------- 1 rao admin 42 May 12 13:09 hello

Ø Directories:

These are a special kind of file that contains a list of other files. Although there is a one-to-one mapping of inode to disk blocks, there can be a many-to-one mapping from directoryentry to inode. When viewing a directory listing using the ls -l command, you can identifydirectories by their permissions starting with the d character.

———drwx------------- 2 rao admin 512 May 12 13:08 public_html

Ø Hard Links:A hard link is actually a normal directory entry except instead of pointing to a unique file, itpoints to an already existing file. This gives the illusion that there are two identical files whenyou do a directory listing. Because a hard link shares an inode, it cannot exist across filesystems. Hard links are created with the ln command. For example, given this directorylisting using ls -l, we see:

-rw------------- 1 rao admin 42 May 12 13:04 hello

When you type $ ln hello goodbye and then perform another directory listing using ls -l,you see:

-rw------------- 2 rao admin 42 May 12 13:04 goodbye

-rw------------- 2 rao admin 42 May 12 13:04 hello

Notice how this appears to be two separate files that just happen to have the same filelengths. Also note that the link count (second column) has increased from one to two. Howcan you tell they actually are the same file? Use $ ls -il. Observe:

13180 -rw------------- 2 rao admin 42 May 12 13:04 goodbye

13180 -rw------------- 2 rao admin 42 May 12 13:04 hello

You can see that both point to the same inode, 13180.

Ø Symbolic Links:

A symbolic link (sometimes referred to as a symlink) differs from a hard link because itdoesn’t point to another inode but to another filename. This allows symbolic links to exist

MSIT 3A Linux Internals 91

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 91: MSIT 3A

across file systems as well as be recognized as a special file to the operating system. Symboliclinks are created using the ln -s command. A common thing people do is creating a symboliclink to a directory that has moved. For example, if you are accustomed to accessing thedirectory for your home page in the subdirectory www, but at the new site you work at,home pages are kept in the public_html directory, you can create a symbolic link from wwwto public_html using the command ln -s public_html www. Performing an ls -l on the resultshows the link.

drwx------------- 2 rao admin 512 May 12 13:08 public_html

lrwx------------- 1 rao admin 11 May 12 13:08 www -> public_html

Ø Sockets:

Sockets are the means for UNIX to network with other machines. Typically, this is doneusing network ports; however, the file system has a provision to allow for interprocesscommunication through socket files. If you need to remove a socket file, use the rm command.Socket files are identified by their permission settings beginning with an s character. An ls -l on a socket file looks something like this:

srwxrwxrwx 1 root admin 0 May 10 14:38 X0

Ø Named Pipes:

Similar to sockets, named pipes enable programs to communicate with one another throughthe file system. You can use the mknod command to create a named pipe. Named pipes arerecognizable by their permission settings beginning with the p character. An ls -l on a namedpipe looks something like this:

prw------------- 1 rao admin 0 May 12 22:02 mypipe

Ø Character Devices:

These special files are typically found in the /dev directory and provide a mechanism forcommunicating with system device drivers through the file system one character at a time.They are easily noticed by their permission bits starting with the c character. Each characterfile contains two special numbers, the major and minor. These two numbers identify whichdevice driver that file communicate. An ls -l on a character device looks something like this:

crw-rw-rw- 1 root wheel 21, 4 May 12 13:40 ptyp4

Ø Block Devices:

Block devices also share many characteristics with character devices in that they exist in the/dev directory. They are used to communicate with device drivers. They have major andminor numbers. The key difference is that block devices typically transfer large blocks ofdata at a time versus one character at a time (A hard disk is a block device, whereas a

Chapter 5 - File System92

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 92: MSIT 3A

terminal is a character device). Block devices are identified by their permission bits startingwith the b character. An ls -l on a block device looks something like this:

brw------------- 2 root staff 16, 2 Jul 29 1992 fd0c

5.3 DIRECTORY POINTER

Directories are files that list other files. It can be normal files or directories. Also enables a hierarchyto be built. Each directory entry consists of two parts: a file name and an inode number. (An inode isroughly a pointer to a file, see table)

The topmost directory is always called /. i.e called the filesystem ‘root’. Directory information canonly be changed by Linux itself. It also ensures a proper structure to be maintained.

5.4 DIRECTORY HIERARCHY

MSIT 3A Linux Internals 93

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 93: MSIT 3A

Ø By tradition several directories have specialized roles

Ø User-installed programs typically go under the /usr/local hierarchy

Ø /mnt is not always present, it is merely a convenience to place all ‘mounted’ devices underone place

5.5 PATHNAMES

Fig. 5.1 Pathname

Ø Files can be referred to by relative or absolute pathnames

$ cd /usr/sbin/httpd

$ cd usr/local/bin/safe-mysqld

Absolute pathnames begin with /

Chapter 5 - File System94

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 94: MSIT 3A

Ø The absolute pathname refers to one file only.[ reference by root / ]

Ø A relative pathname does not begin with / and describes the path from the current directoryto find a file, [cd .. or .]Example: $ cd sbin/httpd ; $ cd bin/safe ; $ cd ..

5.6 CURRENT DIRECTORYØ When you log in your shell is placed in your home directory. Typically /home/usrname.Ø Superuser typically has /root for a home directoryØ ~ is a synonym for /home/usrname.Ø cd changes your current directory, Typing cd path changes your current directory to path.Ø path can be absolute or relative.Ø Without arguments cd changes to your home directory.Ø pwd tells you the current directory.

5.7 DOT (.) AND DOTDOT(..)

Ø Directories always contain two entries “.” and “..”Ø Used for relative pathnames and navigation.Ø Example:

Ø This last row above shows forced execution of a particular file. If we had simply typed a.outthen our PATH environment variable would be used to search for the file.

MSIT 3A Linux Internals 95

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 95: MSIT 3A

Ø It may execute another a.out instead of the one we actually want.

5.8 MOVING AND COPYING FILESØ The mv command is used to move files:

$ mv oldname newname$ mv somefile ..

Ø The cp command is used to copy files:$ cp thisfile newfile$ cp file1 file2 file3 /tmp

Ø Full details of applicable options and usage can be found by typing man mv or man cp.

5.9 REMOVING FILESØ Files are removed using the rm command:

$ rm thisfile thatfile

rm: remove ‘thisfile’? y

rm: remove ‘thatfile’? y

$

Ø Most notable among the options are :

Example: $ rm –r somedir

Ø Again, full details are available by typing man rm.

Ø Removing a file is not considered an operation on the file, It is an operation on the directory.Filenames are merely links.

Chapter 5 - File System96

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 96: MSIT 3A

5.10 OPERATIONS ON DIRECTORIES

Ø These commands can take many arguments.

Ø mkdir can be told to create the whole pathname of directories if they don’t exist.

Example: $ mkdir –p /home/lee/new1/test/directory

ð Will create the directories

/home/lee/new1 and /home/lee/new1/test as well as

/home/lee/new1/test/directory if they don’t already exist.

ð ls arguments control what information is shown and how it’s sorted, Some are explainedlater, consult $man ls for full details.

5.11 INODESØ Each file is represented by an inode.

Ø An inode contains information about:

ð File type (ordinary, directory, FIFO, block device etc.)ð Owner ID (user the file belongs to)ð Size (in bytes)ð Access, creation, and modification timesð Group ID (group the file belongs to)ð File permissionsð Mapping of the file contents (data sectors)ð Inode layout and location varies with filesystem type

Ø The term inode was invented by Dennis M. Ritchie of AT&T.

MSIT 3A Linux Internals 97

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 97: MSIT 3A

5.12 OPTIONS OF INODESExample: $ ls -i displays inode numbers of entries.

Ø stat prints the inode contents for files including permissions, size, links, access times etc.

5.13 LINKSØ More than one filename can refer to an inode, These file names are links to the file.

Ø ln creates links to files.

ð Creates hard links by default.ð ln -s creates symbolic or soft links.

Ø Erasing a file just removes its directory entry, The file is only lost when all entries or it havebeen removed.

Ø Crucially : A filename is not the file

ð The inode is the file

ð All names are simply links (references) to the inode

ð Vague resemblance to Windows’ ‘shortcuts’

Chapter 5 - File System98

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 98: MSIT 3A

5.14 HARD LINKSØ A hard link is merely a directory entry with the relevant inode number

♦ Consider the following

ð Start with:

ð We create a hard link:

Ø Note: Hard links cannot cross filesystems.

Ø Inode numbers are filesystem specific.

5.15 SOFT LINKSØ Soft links store the pathname of the linked file.

Ø This means they can cross filesystems.

MSIT 3A Linux Internals 99

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 99: MSIT 3A

Ø Adding a soft link :

Ø If we replace the test file with another then the symbolic link still works, but the hard one stillpoints to the old file!

5.16 ACCESS CONTROL AND UIDØ File access can be limited to specific users.Ø Super user(s) can override access control.Ø Access control is set by user and group ID.Ø Each user has a user-id (UID) and one or more group-ids(GIDs)Ø Processes have an associated UID and GID, Inherited from the user who created the process.Ø They can however can be changed:

ð Processes are known as set-user ID (setuid) if they set their own user ID.ð or set-group ID (setgid) if they set their own group ID.

Chapter 5 - File System100

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 100: MSIT 3A

5.17 CATEGORIES OF ACCESS CONTROLØ There are three categories of access

5.19 CHANGING ACCESS PREVILEGES: CHMODØ Only the owner of a file (or the super-user) may alter its access permissions.

Ø chmod (change mode) changes access permissions. Works in two ways, symbolically ornumerically. Symbolically is easier to remember (for most).

Ø These may be specified for three sets of users:

ð Userð Groupð Everyone

5.18 ACCESS CONTROL – EXAMPLEØ Example: $ ls -l shows the access permissions.

MSIT 3A Linux Internals 101

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 101: MSIT 3A

5.20 CHMOD SYMBOLICALLYØ Select who you want to change permissions for (u=user, g=group, o=others, a=all}.Ø Decide whether you want to grant a permission (+), remove(-), or set(=) it.Ø Take the permission that you want to change (r=read, w=write, x=execute).

Example: $ chmod gu+w filename Adds write permission for user and group.

Ø You can make several changes by separating the settings with commas.Example: $ chmod a-w,gu=rw filename Removes write permission for all, then grants itfor the user and group.

5.21 CHMOD NUMERICALLYØ Once you know this it is often quicker, A number represents each permission type.

ð 4 read permissionð 2 write permissionð 1 execute permission

Ø Add up the permission numbers you want for each user group (owner, group, all) and supplythese to chmod.

Example: $ chmod 755 filename grants all permissions to the owner (4+2+1), and read andexecute (4+1) to group and all others.

5.22 UMASK MASKING PRIVILEGESØ Files begin with a default access setting, Specified by a user’s umask setting.Ø This only works numerically, Unlike chmod, specified permissions are turned offØ With a umask setting of 000 files are created with permissions rw-rw-rw- (666).Ø Default umask is 022 which means files are typically created rw-r—r— (644).

Example:

Chapter 5 - File System102

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 102: MSIT 3A

5.23 FILE SYSTEM STRUCTUREMulti-Volume Filesystems of linux.

Ø The filesystem can be held on several devices.

Ø Large disks can be divided into partitions, This creates several logical devices.

Ø A basic Linux system must be present on /.

Ø Other parts of the fs may be mounted at any time.

Ø The main ones are mounted at boot time.

Ø This is controlled by the /etc/fstab file which says what volumes are mounted where. [/etc/mtab also gives volume information]

5.24 /ETC/FSTAB – EXAMPLE

5.25 SPECIAL FILES - /DEVØ Files under /dev typically represent devices attached to your computer.

Ø Programs can open and close them and read from and write to them - as with regular files.

Ø Kernel code exactly handles and extracts work from these.

Two types:-

ð Block Special- Disk drives, tape drives, CDROMs.

ð Character Special- Printers, modems, etc

MSIT 3A Linux Internals 103

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 103: MSIT 3A

5.26 SPECIAL FILES - /PROCØ The section of the filesystem called /proc doesn’t contain real files.

Ø It contains system status information.

For example:

Table 5.1 : System Information from /proc

5.27 MOUNTING ADDITIONAL VOLUMESØ To mount a filesystem use mount command.

For example: $ mount /dev/cdrom /mnt/cdrom

Ø Mounts the filesystem /dev/cdrom in the directory /mnt/cdrom.

Ø $ cd /mnt/cdrom changes directory to the root of the CDROM’s filesystem.

Ø To unmount use $ umount name where name is either the filesystem name or the mountpoint:

$ umount /dev/cdrom

$ umount /mnt/cdrom

Chapter 5 - File System104

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 104: MSIT 3A

Ø A filesystem can only be unmounted when it is no longer in use. ‘In use’ includes:

ð Having any file on that filesystem open.

ð Having a shell in a directory on that filesystem.

5.28 MOUNTING SHARED FILESYSTEMSØ NFS filesystems can be mounted with

Example: $ mount –t nfs hostname:path mount-point

$ mount –t nfs landlord:/backup /mnt/backup

Ø Share files from MS-Windows machines using SAMBA.

Ø This is a free implementation of the Windows file-sharing protocols.

Example: $ mount –t smbfs ’\\ntbox\c’ /mnt/ntbox

Ø Linux does not use the ‘drive letter’ concept at all.

Ø Drives and shares integrate seamlessly into the filename tree.

5.29 SUMMARYØ The primary Linux filesystem is Ext2. It has a tree-like hierarchy of directories. Directories

merely contain pointers to files(inodes).

Ø inodes contain all the information about a file. Also can have multiple links to the same file.Read/Write access is controlled per file. Creation/Deletion of files is controlled by permissionsof the directory. Several filesystems can be mounted to create the directory hierarchy.

Ø This chapter described the basic overview of how to use a command shell. There is a lotmore, which would be very useful especially when writing shell scripts or performing advancedtasks. However the above should be serve as a good beginning to understand what is goingon in the system, as well as a starting point from which you can learn more details aboutLinux shell programs.

Ø Remember that the bash shell has its own man page, as well as longer tutorials anddocumentation available at the Linux Documentation Project website.

MSIT 3A Linux Internals 105

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 105: MSIT 3A

5.30 CHECK YOUR PROGRESS

I. Exercises1. Basic navigation

(a) Log in and use pwd to discover what the full path of your home directory is.

(b) Change directory to /bin and then /tmp. Use pwd to check you got there each time.

(c) When in /tmp type cd .. and use pwd to find out where you end up.

(d) What is the parent directory of the root of the filesystem? Why is this so?

(e) Move back to your home directory. Think of three ways you can do this.

2. Directories

(a) Start in your home directory and create a directory called new.

(b) Change to the new directory and create a directory called newer.

(c) Go to you home directory. Now create a directory under newer called newerstill. Thereare two ways to do this what are they? (Hint: You don’t have to change directories to solvethis.)

(d) Remove all the directories that you’ve just created, there are several ways to do this.

(e) Create the same directory structure with one command.

3. Links

(a) Create a file called test in your home directory (Typing echo 123> test should do this).Now create a hard link to test called h_test and a symbolic link to test called s_test.

(b) Find out the inode number of the files. Check you understand why they are what they are.

(c) Remove the original file called test. Can you still get at the contents of the original file?

(d) What happens if you try cat s_test. Make sure you understand the distinction betweenh_test, and s_test.

(e) Try to make a hard link to your home directory. Why does this fail?

4. /proc

(a) Use the files in /proc to find out how much memory your system has and what processor itis running on.

(b) Find out what PCI devices are attached to your machine.

Chapter 5 - File System106

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 106: MSIT 3A

(c) Find out what environment variables are set for your currently running shell using theinformation in /proc. Hint you can get the process-id of your shell using $$.

(d) Whether or not your machine is doing IP forwarding is stored in the file /proc/sys/net/ipv4/ip_forword. You can cat this file, a value of 1 means that

IP forwarding is turned on. Find out whether or not your machine will forward IP.

(e) Find out how many files are currently open on your system.

II. Choose appropriate answer1. File contains _____.

a. digitally encoded pictures b. program c. sound d. all of these.

2. In case of ___________ pathname ,the path starts from root.

a. absolute b. relative c. both of these d. none of these

3. _______ command used to change the permissions of your files & directories.

a. ls b. chmod c. more d. ls -F

4. chmod 555 dirname is used ____________________________.

a. To protect the files in a directory and all its subdirectories from everyone else on yoursystem.

b. To keep yourself from accidentally removing files in a directory.

c. To let other people on the system see what’s in a directory - and read or edit the files ifthe file permissions let them - but not rename, remove, or add files.

d. none of the above.

5. chmod 644 filename is used to________________________.

a. To let non group users read but not edit the file

b. To let anyone read or edit the file

c. To make a private file that only you can edit

d. none of the above.

6. For using FTP ____________________________.

a. Both computers don’t need to be running LINUX

MSIT 3A Linux Internals 107

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 107: MSIT 3A

b. Both computers need to be running LINUX

c. one computer must be running LINUX & other any operating system

d. none of the above.

7. The acronym for EXT2 is ________________________.

a. Second Extended File system

b. Extended File system

c. Expanded File system

d. all of the above

8. mount command contains the ____________.

a. physical block device that contains the file system

b. name of the file system

c. both of above

d. none of these

III. Say True or False1. A directory is actually a special kind of file. True/False

2. In case of absolute pathname, the path starts from your working directory. True/False

3. ls -l puts a / (slash) at the end of each directory name. True/False

4. chmod 755 dirname gives full access to everyone on the system. True/False

5. chmod 664 filename allows nongroup users to read but not edit the file True/False

6. Filenames can have any character including /. True/False

IV. Essay type Questions1. Briefly explain the concept of LINUX file system..

2. Explain the following:

i. PATHii. Absolute pathname and relative pathname.iii. Files in the Directory Tree.

Chapter 5 - File System108

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 108: MSIT 3A

iv. Directory Access Permissionv. File Access Permission

3. Differentiate among chmod & umask.

4. Explain all the attributes related to ls –al .

5. Describe the concept of File Management.

6. Write a note on the following filesystems

i /dev ii /poc

7. what is uid? does it relate with access control mechanism of files.

8. How to mount a Shared File system.

9. What is a link? Justify your answer by giving proper examples for its types.

V. Further readings and other activities1. Get more information using man or info or any help command for sh, bash, csh, ksh, inode, fs, env,

set, mount, mknd, id, dev, stat.

2. For further readings you can refer the following books

Ø Title: Linux internals

Auihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga http://www.pandurangarao.i8.com/doc/linux/linuxbook.html

http://www.raomvp.bravepages.com/doc/linux/linuxbook.htmlA complete reference for you to get more information.You can also extract solutions for exercises.

Ø More information on filesystem can be obtained from text booktitle: Introduction to the Shell programming

Author: Yashwanth Kanetkar

VI. Solutions

I. Exercises1. Basic Navigation

(a) You will probably see

$ pwd

MSIT 3A Linux Internals 109

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 109: MSIT 3A

/home/usernamewhere username is the name you log in with.

(b) Check that the output of pwd is /bin and /tmp.

(c) You should end up in /. This is the root of the filesystem.

(d) The parent of / is itself. You can use ls -lia to show that the inode numbers for . and .. are thesame when you are in /.

(e) You can move back to your home directory by using any of the following: i. cd ii. cd ~ iii. cd/home/username (Provided your home directory lives under /home)

2. Directories

(a) $ cd ; $ mkdir new (b) $ cd new ; $ mkdir newer

(c) $ cd ; then either:

i. $ cd new/newer ; $ mkdir newerstill

ii. $ mkdir new/newer/newerstill

(d) Any of the following will work :

i. $ cd ; $ cd new/newer ; $ rmdir newerstill ; $ cd .. ;

$ rmdir newer ; $ cd .. ; $ rmdir new

ii. $ cd ; $ rmdir –p new/newer/newerstill ;

iii. $ cd ; $ rm –fr new/

(e) $ cd ; $ mkdir –p new/newer/newerstill

3. Links

(a) This is achieved as follows:

$ ln test h_test

$ ln –s test s_test

(b) ls -li should show that the inode number of the original file and h_test are identical, h_testis another name for the original file. The inode number for s_test will be different. It is aseparate file that contains information about the location of the file it is a link to.

(c) After you created the hard link the original file had two names test and h_test. You haveremoved test but until all names for a file have been removed it is still accessible. In thiscase you can do cat h_test to see the contents of the file.

Chapter 5 - File System110

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 110: MSIT 3A

(d) This should fail with a No such file or directory message. s_test contained a pointer to thefile test not the inode number. There is no longer a file named test so this cannot work.Hard links reference a file by its inode number, symbolic links reference it by its name.

(e) This is not allowed, as it could stop the filesystem being strictly hierarchical.

4. /proc

(a) cat /proc/meminfo should show you memory usage.

(b) cat /proc/pci gives a list of all PCI devices.

(c) cat /proc/$$/environ will give a list of the environment of your current shell.

Each variable is delimited with the nul character (decimal 0). The following will show theoutput with one variable per line :

$ cat /proc/$$/environ | tr ‘\verb|\|000’ ‘\verb|\|n’

(d) See The Exercise -

(e) $ cat /proc/sys/fs/file-nr

II. Choose appropriate answer1.d 2. a 3.b 4.b 5.d 6.a 7.a 8. c

III. Say True or False1. True 2. False 3. True 4. False 5. True 6. False

MSIT 3A Linux Internals 111

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 111: MSIT 3A

Chapter 6

File System Administration

6.0 INTRODUCTION AND OBJECTIVES

Presented in this chapter are the fundamentals and many useful specifics of the Bourne again shell,currently the most popular of the Linux shells for execution of application programs. Also describedare the steps to organize file system and script shell commands, a detailed coverage on partitioning

methods of hard disk. Creation and analysis of links, inodes are justified. Disk recovery techniques,maintenance and and space information also enumerated.

OBJECTIVESAfter completing this module you should be able to understand and utilize these features of the Linux

filesystem:

ð Inode parameters

ð Links creation and analysis

ð Links: relationship with inode

ð Non-native filesystem types

ð Native filesystems types

ð Filesystem checking and recovery

ð Disk usage and free space

ð Disk partitioning utilities

Chapter 6 - File System Administration112

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 112: MSIT 3A

ð Problems with LILO and partitions

ð Filesystem creation

ð A detailed look at fdisk()

ð Block, character and ‘raw’ Devices

6.1 INODE IN DEPTHØ Every file/directory is specified by an inode.

Ø A single inode can have many filenames (links).

Ø An inode contains information about:

ð File type (ordinary, directory, FIFO, block device etc.).

ð Owner ID (user the file belongs to).

ð Size (in bytes).

ð Access, creation, and modification times.

ð Group ID (to which group does the file belong).

ð File permissions.

Ø Mapping of the file contents (data sectors).

Ø Knowing inode numbers can be very useful if you want to restore files on a disk with badblocks.

Ø Inode layout and location varies with fs type.

6.2 INODE TABLE ENTRYØ An inode maintains information about each file. Depending on the type of file system, the inode

can contain upwards of 40+ pieces of information. Most of it, however, is only useful to the kernel anddoesn’t concern us. The fields that do concern us are

mode The permission mask and type of file.

link count The number of directories that contain an entry with this inode number.

user ID The ID of the file’s owner.

group ID The ID of the file’s group.

MSIT 3A Linux Internals 113

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 113: MSIT 3A

size Number of bytes in this file.

access time The time at which the file was last accessed.

mod time The time at which the file was last modified.

inode time The time at which this inode structure was last modified.

block list A list of disk block numbers which contain the first segment of the file.

indirect list A list of other block lists.

Ø The modes, link count, user ID, group ID, size and access time are used when generating filelistings. Note that the inode does not contain the file’s name. That information is held in the directory file(see below for details).

Ø Example: ls –i displays inode numbers of filenames.

Ø stat prints the inode contents for files including permissions, size, links, access times etc.

6.3 LINKS: RELATIONSHIP WITH INODEØ More than one filename may refer to an inode. These file names are links to the file.

Ø ln creates links to files.

Chapter 6 - File System Administration114

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 114: MSIT 3A

ð Creates hard links by default.

ð ln –s creates symbolic or soft links.

Ø Erasing a file simply removes its directory entry. Only when all entries for a file have beenremoved is the file lost.

Ø Crucially : A filename is not the file, The inode is the file.

Ø All names are simply links (references) to the inode

6.4 HARD LINKSØ A hard link is merely a directory entry with the relevant inode number.

Consider the following, We start with : $ ls –li

We create a hard link :

Note: Hard links cannot cross filesystems. Inode numbers are filesystem specific.

6.5 SOFT LINKSØ Soft links store the pathname of the linked file. This means they can cross filesystems.

Ø Adding a soft link :

MSIT 3A Linux Internals 115

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 115: MSIT 3A

Ø If we replace the test file with another then the symbolic link still works, the hard one still pointsto the old file!

6.6 NON-NATIVE FILESYSTEMSØ Besides Ext2, Linux supports most well known filesystems.

Ø Example: MS-DOS (FAT16), VFAT, FAT32, ISO9660 (CD-ROM), NTFS (Windows NT),SMB / CIFS (MS Windows file sharing).

Ø Most can be mounted, read & written.

Ø Specific tools can create some non-native filesystems (e.g. DOS/CD-ROM).

Ø Some non-native filesystems can even be checked and repaired (e.g. Minix).

Ø Not wise to automate checking and repair on non-native systems.

6.7 DISK CHECKING AND RECOVERY (FSCK)Ø fsck checks and repairs Linux filesystems.

Ø GENERIC SYNTAX:

Ø Actually, just a front-end for specific filesystem checkers , e.g. e2fsck

Ø The filesystem-specific checker is searched for in these places in this order:

ð /sbin.

ð /etc/fs and /etc.

ð Directories in the PATH environment variable.

Chapter 6 - File System Administration116

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 116: MSIT 3A

Ø Common options:

ð -A uses /etc/fstab to ID and check all filesystems in one run.

ð -R skips the root filesystem when the -A option is operative.

6.8 CHECK A LINUX EXT2 FILESYSTEM (E2FSCK)Ø e2fsck is the application called by fsck to check ext2 filesystems.

Ø SYNTAX $ e2fsck [options] device

Ø Devices specified as /dev/hdXX, /dev/sdXX, etc.,

Ø Main options:

6.9 DISK FREE SPACE (DF)Ø df shows free space on filesystems.

Ø SYNTAX: $ df [options] [filesystem list]

Ø Defaults to all currently mounted filesystems. Displays in 1K blocks by default; environmentvariable POSIXLY_CORRECT sets 512-byte

Ø GNU df can’t show space on unmounted filesystems.

Ø Main options:

MSIT 3A Linux Internals 117

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 117: MSIT 3A

6.10 DISK USAGE (DU)Ø du reports disk space used by a directory, including its sub-directories or a file.

Ø Useful for summarizing file/directory sizes.

Ø SYNTAX: $ du [options][pathlist]

Ø GNU du defaults to 1K blocks, unless set POSIXLY_CORRECT (512-byte).

6.11 DISK PARTITIONING CONCEPTSØ Partitioning enables efficient use of large drives by dividing them into smaller sections.

Ø A Partition table at the start of each disk points to the beginning or end of each partition.

Ø Max 4 Primary Partitions on standard disks.

Ø More possible inside Extended Partitions.

Chapter 6 - File System Administration118

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 118: MSIT 3A

Ø An Extended Partition has its own partition table; pointing to sub-divisions within it.

Ø Sub-divisions called Logical partitions (drives).

6.12 A PARTITIONED DISK

Figure 6.1 shows a partitioned disk

6.13 MAKING AND CHANGING PARTITIONSØ Linux usually benefits from putting parts of its filesystem on different drives or partitions.

Example: access different parts simultaneously.

Ø Issues:

ð How many partitions?

ð Size of partitions for specific directories.

ð Partitioning an empty drive.

ð Destructive re-partitioning.

ð Non-destructive re-partitioning.

MSIT 3A Linux Internals 119

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 119: MSIT 3A

6.14 HOW MANY PARTITIONS?Ø How many partitions you need depends on:

ð How you intend to use a system.

ð What resources you have (e.g. physical disks).

Ø A common single-disk server might have separate partitions for:

ð Swapping.

ð The / filesystem/directory

ð The /boot filesystem/directory

ð The /home filesystem/directory

ð The /usr filesystem/directory

ð The /var filesystem/directory

ð The /usr/doc filesystem/directory

6.15 WHAT SIZE PARTITIONS?Ø What size partitions you need depends entirely upon how you intend to use the system.

Ø Filesystems needing large partitions are usually:

ð /home for users’ file space.

ð /var for server files (news, web, mail, logs etc).

Ø The following are usually made just big enough:

ð the swap partition (rarely more than 127 Mb).

ð /boot (enough for a few alternative kernels).

6.16 BIOS PROBLEMS WITH LILO AND PARTITIONSØ BIOSes on most Intel-type machines can’t access data beyond cylinder 1023.

Ø To start Linux, LILO uses data in /boot.

Ø The /boot partition must always be located entirely below cylinder 1023.

Chapter 6 - File System Administration120

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 120: MSIT 3A

Ø Multiple IDE drive machines always work /boot is on the first primary controller.Ø On mixed IDE/SCSI systems /boot must be on the first IDE primary controller

or SCSI ID 0.Ø On multiple SCSI drive systems /boot must be on ID 0 or ID 1.

6.17 DISK PARTITIONING TOOLS

Common partitioning tools:

6.18 USING FDISK()Ø fdisk basically writes partition tables. Very dangerous, but not that difficult.

Ø SYNTAX: $ fdisk [options][disk-device-name]

Ø One useful CLI option: -l lists available partition tables then exits.

Ø Usually super user-only and needs explicit path.

Ø 2 tips:

v Never use w (write/save changes) unless you really know what you are doing.v Use q (quit) to exit without saving changes.

MSIT 3A Linux Internals 121

Tool Notes

fdisk Standard on all Linux and much UNIX.Very Flexible. Tricky character-basedinterface, Fairly reliable

fipa Non-destructive re-sizing of partitionsDifficult CLI. Some distrust it.

Disk Druid Red Hat install-time tool. Friendliercharacter-based interface. Setgrowable partitions. Set mount points

Partition Used in Caldera X-based installation.Magic Lite Allows non-destructive repartitioning on

the fly. Easy and reliable. Proprietory.Not always available

Partition As above, but the full commercialMagic product and price

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 121: MSIT 3A

6.19 THE FDISK INTERFACEØ The only helpful thing about fdisk screens is that they all prompt with (m for help).

Ø Launched without arguments on IDE:

[root@jnnce]# /sbin/fdisk

using /dev/hda as default device!

Command (m for help):

v p prints the partition table for current hard disk.

6.20 INTERACTIVE COMMANDS IN FDISKØ A selection of fdisk interactive commands:

Chapter 6 - File System Administration122

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 122: MSIT 3A

6.21 MAKING LINUX FILESYSTEMS (MKE2FS)Ø Normally, you can only write a file to a device with a filesystem on it.

Ø Native Linux filesystems are made using mke2fs.

Ø Utilities for other types: mkdosfs, mkisofs, etc.,

Ø SYNTAX: $ mke2fs [options] device

Ø Filesystems are made on un mounted devices.

Ø If omitted, mke2fs auto-calculates fs size.

Ø Lots of options, few widely used:

6.22 BLOCK DEVICESØ Typically, block devices are disks and tapes.

Ø Strictly, I/O devices with these characteristics:

ð Seen by kernel as a range of blocks 0 to n-1.

ð Where n = number of blocks on the device.

ð Can have a filesystem mounted on it.

ð Ability to perform random access reads.

ð A specific block size.

ð Handling only one data block at a time.

ð Only accepts actions on whole data blocks.

ð Kernel buffers its I/O.

MSIT 3A Linux Internals 123

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 123: MSIT 3A

6.23 CHARACTER DEVICESØ Any device which is not a block device.

Typically:

ð printersð terminalsð modems

Ø Drivers determine how a program reads from and writes to it.

Ø For example, a terminal device driver lets programs read typed info in two ways:

ð In raw mode (i.e without driver interpretation).ð A line at a time with the driver removing erase and kill chars (typos and corrections),

so:

v The program reads everything on a line.v The number of characters on a line can vary.

Ø Kernel doesn’t buffer character devices

6.24 SUMMARY

Commands used to manage file systemsØ badblocks(8) - Search a device for badblocks. The command “badblocks /dev/hda” will

search the first partition of the first IDE hard drive for badblocks.

Ø cfdisk(8) - A partition table manipulator used to create or delete disk partitions.

Ø dosfsck(8) - Used to check a msdos filesystem.

Ø dumpe2fs(8) - Lists the superblock and blocks group information on the device listed. Usewith a command like “dumpe2fs /dev/hda2”. The filesystem on the device must be a Linuxfilesystem for this to work.

Ø fdformat(8) - Performs s lowlevel format on a floppy disk. Ex: “fdformat /dev/fd0H1440”.

Ø fdisk(8) - Used to add or remove partitions on a disk device. It modifies the partition tableentries.

Ø fsck(8) - Used to check and/or repair a Linux filesystem. This should only be used on systemsthat are not mounted.

Chapter 6 - File System Administration124

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 124: MSIT 3A

Ø hdparm(8) - Used to get or set the hard disk parameters.

Ø mkdosfs(8) - Used to create a msdos filesystem.

Ø mke2fs(8) - Create a Linux native filesystem which is called a second extended filesystem.This creates the current version of the Linux filesystem.

Ø mkfs(8) - Used to make a Linux filesystem on a device. The command “mkfs /dev/hdb1”will create a Linux filesystem on the first partition of the second IDE drive.

Ø mkswap(8) - Creates a Linux swap area on a device.

Ø mount(8) - Used to mount a filesystem. It supports many types of filesystems.

Ø stat(1u) - Used to print out inode information on a file. Usage: stat filename

Ø swapoff(8) - Used to de-activate a swap partition.

Ø swapon(8) - Used to activate a swap partition.

Ø tune2fs(8) - Used to adjust filesystem parameters that are tunable on a Linux second extendedfilesystem. The filesystem must not be mounted write when this operation is performed. Canadjust maximum mount counts between filesystem checks, the time between filesystemchecks, the amount of reserved blocks, and other parameters.

Ø umount(8) - Unmount a filesystem.

6.25 CHECK YOUR PROGRESS

I. Exercises1. Inodes and Linking.

(a) Use stat to find out the number of hard links to your / directory.

(b) Use the following to locate the files with inode numbers 1 and 3:

$ find / -inum inode-number

(c) Create a file called test in your home directory (Typing echo > test should do this). Nowcreate a hard link to test called h_test and a symbolic link to test called s_test

(d) Find out the inode number of the files. Check you understand why they are what theyare.

(e) Remove the original file called test. Can you still get at the contents of the original file?

MSIT 3A Linux Internals 125

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 125: MSIT 3A

(f) What happens if you try cat s_ test. Make sure you understand the destinction betweenh_test and s-_ test.

(g) Try to make a hard link to your home directory. Why does this fail?

2. Creating Filesystems and Formatting.

(a) Identify and use the command string needed to create the following on a floppy disk:i. An Ext2 filesystemii. A DOS filesystemiii. An IS09660 CD-ROM filesystem

(b) To test your DOS filesystem, cp a long filename file to it. What happens to the filename?

(c) Mount the ISO9660 formatted disk under /mnt/floppy to prove it is readable.

(d) Identify and use the command string needed to do the following to a floppy disk:

i. Low-level format the disk.

ii. Add a DOS fs to a low-level formatted disk.

(e) Try using tar to write to a floppy disk without a filesystem on it (you may have to low-levelformat the disk to remove an existing fs).

3. Checking and Repairing Filesystems.

(a) Find the appropriate man pages and, hence commands to:

i. Locate bad blocks on an Ext2 device.

ii. Find and mark the bad blocks on DOS/FAT floppies.

(b) Use e2fsck to force checking and automatically repair an Ext2 formatted floppy.

4. Creating, Modifying and Deleting Partitions.

It is not wise to practice disk partitioning on important filesystems. It can be done, but mistakes may beunrecoverable. So we ask you to do the following partitioning questions on a floppy. Most people won’t beable to make mountable filesystems on a floppy (you need to make a block device file first), but you shouldget some safe practice on fdisk. You may only be able to do these floppy-based questions using recentversions of fdisk.

(a) Delete all existing partitions from your floppy.

(b) Create 2 new primary partitions:i. 1 with an Ext2 system IDii. 1 with a Win95 FAT32 system ID.

Chapter 6 - File System Administration126

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 126: MSIT 3A

(c) Save the new partition table and exit fdisk.

(d) Re-enter fdisk and check the floppy’s partition table contains the correct partitions.

(e) Delete the FAT32 partition and replace it with two FAT32 logical drives.

II. Choose the correct answer:1. Every file / directory is specified by an _____.

a) Link b) inode c) name d) all of these.

2. ln creates links to ___________.

a) files b) system programs c) Application programs d) all of these.

3. ln -s creates _____ links.

a) Kernel b) shell c) symbolic or soft d) all of these.

4. Ext2 is _________________________.

a) Network File System

b) Native File System

c) NetBios System

d) None of the above

5. ____ checks and repairs Linux filesystems.

a) fips

b) diskdruid

c) fsck

d) All of the above

III. Say True or False

1. e2fsck is the application called by fsck to check ext2 filesystems. True/False

2. df shows free space on filesystems. True/False

3. Native Linux filesystems are made using mke2fs. True/False

4. character devices are disks and tapes True/False

MSIT 3A Linux Internals 127

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 127: MSIT 3A

IV. Essay Type Questions1) What are block, character and raw devices? Write brief information.

2) Explain with options e2fsck.

3) Explain the changes in filesystem when du and df commands are executed.

4) Explain how the recovery of Linux filesystems are made.

5) Describe how the Native Linux filesystems are made? Give the types.

6) Desctibe the inode table entries in detail.

7) Elucidate common disk partitioning tools.

8) Mention all fdisk interactive commands.

V. Further readings and other activities1. Get more information using man or info or any help command for

e2fsck, du, df, tty, passwd, group, ln

EX: 1. $ man du 2. $ apropos bash

Check the amount of space used, amount of space free for different drives and differentdirectories.

2. For further readings you can refer the following books

Ø Title: Linux internalsAuihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimogahttp://www.geocities.com/raomvp/doc/linux/linuxbook.htmlA complete reference for you to get more information.You can also extract solutions for exercises.

Ø Title: principles of unix programmingAuihors: Sumitabha Das

VI. Solutions

I. Exercises1. Inodes and Linking.

(a) The answer depends on your system. In recent Red Hat distributions / is inode number 2.

Chapter 6 - File System Administration128

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 128: MSIT 3A

(b) The answer depends on your system. In recent Red Hat distributions inode number 1 is /proc and number 3 is /proc/uptime.

(c) This is achieved as follows:

$ ln test h_test

$ ln –s test s_test

(d) ls -li should show that the inode number of the original file and h_test are identical h_testis another name for the original file. The inode number for s_test will be different. It is aseperate file that contains information about the location of the file it is a link to.

(e) After you created the hard link the original file had two names test and h_test.

You have removed test but until all names for a file have been removed it is still accessible.In this case you can do cat h_test to see the contents of the file.

(f) This should fail with a no such file or directory message. s_test contained a pointerto the file test not the inode number. There is no longer a file named test so this cannotwork. Hard links reference a file by it’s inode number, symbolic links reference it by itsname.

(g) This is not allowed, as it could stop the filesystem being strictly hierarchical.

2. Creating Filesystems and Formatting.

(a) These are typical solutions, but there are others:

i. $ mke2fs /dev/fd0

ii. $ mkdosfs /dev/fd0

iii. $ mkdosfs /dev/fd0

(b) The filename should be shortened to 8 chars, without warning . . . could be tricky!

(c) Yes, you can mount a floppy drive on Linux with a CD-ROM format. Indeed, you canactually mount an ISO9660 formatted disk image (i.e. a single file) of an entire Linux directorytree. Trust me, it isn’t as daft as it sounds!

(d) Something like this:

i. $ fdformat /dev/fd0h1440

ii. Add a DOS fs to a low-level formatted disk.

(e) Use a command something like this: $ tar –c filenames > /dev/fd0

MSIT 3A Linux Internals 129

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 129: MSIT 3A

3. Checking and Repairing Filesystems

(a) apropos should yield:

i. badblocks (8).

ii. mbadblocks (1).

(b) e2fsck –p –f /dev/fd0

Assuming that your floppy is actually OK, you will hardly get any feedback on stdout.

4. Creating, Modifying and Deleting Partitions.

You probably can’t do these floppy-based questions on old versions of fdisk.

(a) Use $ fdisk /dev/fd0 followed by the d interactive command.

(b) Use the n interactive command twice, followed by:

i. command (m for help): t

Partition number (1-4): 1

Hex code (type L to list codes): 83

ii. command (m for help): t

Partition number (1-4): 1

Hex code (type L to list codes): b

(c) Use the w interactive command followed by the q interactive command.

(d) $ fdisk /dev/fd0 followed by the p interactive command

(e) Your screen should look something like this:

command (m for help): dpartition number (1-4): 2command (m for help): n

Chapter 6 - File System Administration130

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 130: MSIT 3A

command action

e extended

p primary partition (1-4)

e

command (m for help): p

Disk /dev/fd0: 2 heads. 18 sectors, 80 cylinders

units = cylinders of 36 * 512 bytes

Using default value 41Last cylinder or +size or +sizeM or +sizeK (41-80, default 80): 60command (m for help): ncommand action l logical (5 or over)

p primary partition (1-4)

l

command (m for help): p

Disk /dev/fd0: 2 heads. 18 sectors, 80 cylinders

units = cylinders of 36 * 512 bytes

MSIT 3A Linux Internals 131

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 131: MSIT 3A

command (m for help): t

partition number (1-6): 5

Hex code (type L to list codes): b

Changed system type of partition 5 to b (Win95 FAT32)

command (m for help): t

partition number (1-6): 6

Hex code (type L to list codes): b

Changed system type of partition 6 to b (Win95 FAT32)

command (m for help): p

Disk /dev/fd0: 2 heads. 18 sectors, 80 cylinders

units = cylinders of 36 * 512 bytes

II. Choose the correct answer:1. b 2. a 3. c 4. b 5. d

III. Say True or False1. True 2. True 3. True 4. False

Chapter 6 - File System Administration132

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 132: MSIT 3A

Chapter 7

System Administration

7.0 INTRODUCTION AND OBJECTIVES

So far in this book, you’ve seen how to use Linux for many different tasks. However, there aresome issues we haven’t dealt with because they are used rarely or only by a single administrator(who may be the only user).

This chapter covers the most important things that you need to know about system administrationunder Linux in sufficient detail to start using the system comfortably. In order to keep the chaptermanageable, it covers just the basics and omits many important details.

The general actions a system administrator must perform to keep filesystems performing smoothly arethe following:-

v Check filesystems for corrupt sectors

v Check filesystems for integrity and correct i-node tables

v Check file permissions and ownerships to ensure proper access

v Make filesystems (local and remote) available to users as necessary

v Check the Linux system’s disk space

v Management of users with respect to security and data

v Perform regular backups for data security

MSIT 3A Linux Internals 133

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 133: MSIT 3A

Chapter 7 - System Administration134

ObjectivesAt the end of this unit, You would be able to know and expertise the following concepts of system

administration.

ð The superuser account

ð User accounts /etc/passwd

ð Groups

ð Managing Linux users

ð User reference files

ð User modifications

ð Examples of making changes to permissions

ð Some administration commands

7.1 THE SUPERUSER ACCOUNTØ When the Linux software is installed, one master login is created automatically. This login,

called root, is known as the superuser because there is nothing the login can’t access or do.While most user accounts on a Linux system are set to prevent the user from accidentallydestroying all the system files, for example, the root login can blow away the entire Linuxoperating system with one simple command. Essentially, the root login has no limitations.

7.2 USER ACCOUNTS /ETC/PASSWDØ All the information about user accounts is kept in the file /etc/passwd. The /etc/passwd file

should be owned only by root and have the group ID set to zero (usually root or systemgroup, as defined in the /etc/group file). The permissions of the /etc/passwd file should be setto allow write access only by root, but all others can have read access. (We deal with groupsand permissions later in this section.) The lines in the /etc/passwd file are divided into a strictformat:

v username:password:userID:groupID:comment:home directory:login command

Ø This format can best be seen by looking at a sample /etc/passwd file. The /etc/passwd filecreated when a Linux system is newly installed is shown below.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 134: MSIT 3A

MSIT 3A Linux Internals 135

$ vi /etc/passwdroot::0:0:root:/root:/bin/bashbin:*:1:1:bin:/bin:daemon:*:2:2:daemon:/sbin:adm:*:3:4:adm:/var/adm:lp:*:4:7:lp:/var/spool/lpd:sync:*:5:0:sync:/sbin:/bin/syncshutdown:*:6:0:shutdown:/sbin:/sbin/shutdownhalt:*:7:0:halt:/sbin:/sbin/haltmail:*:8:12:mail:/var/spool/mail:news:*:9:13:news:/usr/lib/news:uucp:*:10:14:uucp:/var/spool/uucppublic:operator:*:11:0:operator:/root:/bin/bashnobody:*:-1:100:nobody:/dev/null:

Ø Each line in the /etc/passwd file is composed of seven fields, separated by a full colon. Ifthere is nothing to be entered in a field, the field is left blank, but the colons are retained tomake sure each line has seven fields (which also means each line will have six colons). Theseven fields (from left to right on each line) are:

user name A unique identifier for the user.

password The user’s password (encrypted).

user ID (UID) A unique number that identifies the user to the operating system.

group ID (GID) A unique number that identifies the user’s group (for file permissions).

comment Usually the user’s real name, but sometimes phone numbers, departments,and so on.

home directory The directory in which users are placed when they log in.

login command The command executed when the user logs in, normally a shell.

7.3 GROUPSØ Group information is maintained in the file /etc/group, which is similar in layout to the /etc/

passwd file. The default /etc/group file from a newly installed Linux system is shown below.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 135: MSIT 3A

Chapter 7 - System Administration136

$vi /etc/grouproot::0:rootbin::1:root,bin,daemondaemon::2:root,bin,daemonsys::3:root,bin,admadm::4:root,adm,daemontty::5:disk::6:root,admlp::7:lpmem::8:kmem::9:wheel::10:rootfloppy::11:rootmail::12:mailnews::13:newsuucp::14:uucpman::15:manusers::100:gamesnogroup::-1:

Ø Each line in the file has four fields separated by colons. Two colons together mean that thefield is empty and has no value specified. Each line in the file follows this format:

v group name:group password:group ID:users

Ø Each group has a line of its own in the file. The fields in the /etc/group file (from left to right)are listed as follows:

v group name- A unique name usually of eight characters or less (usually standardalphanumeric characters only).

v password- Usually left as an asterisk or blank, but a password can be assigned that a usermust enter to join the group. Not all versions of Linux or UNIX use this field, and it is leftin the file for backward compatibility reasons.

v group ID (GID)- A unique number for each group, used by the operating system.

v users- A list of all user IDs that belong to that group.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 136: MSIT 3A

MSIT 3A Linux Internals 137

Ø Every Linux system has a number of default groups which belong to the operating system,usually called bin, mail, uucp, sys, and so on. You can see the system-dependent groups in thedefault /etc/group file as shown by vi editor. In that file, all but the last two entries are systemgroups. You should never allow users to belong to one of these groups because it gives themaccess permissions that can be the same as root’s. Only system logins should have access tothese operating system groups.

7.4 MANAGING LINUX USERSØ Linux Commands for managing users are:

v adduser(8) - Command used to add user accounts.

v chage (1) - Used to change the time the user’s password will expire.

v chfn(1) - Change a user’s finger information

vchsh(1) - Change a user’s shell.

vchgrp (1) - Changes the group ownership of files.

vchown (1) - Change the owner of file(s ) to another user.

v gpasswd (1) - Used to administer the /etc/group file.

v groupadd (8) - Create a new group.

v grpconv (8) - Creates /etc/gshadow from the file /etc/group which converts to shadowpasswords.

v grpunconv (8)- Uses the files /etc/passwd and /etc/shadow to create /etc/passwd, thendeletes /etc/shadow which converts from shadow passwords.

v groupdel (8) - Delete a group

v groupmod (8) - Modify a group

v groups (1) - print the groups a user is in

v grpck (8) - Verify the integrity of group files.

v id(1) - Print group or user ID numbers for the specified user.

v newgrp(1) - Allows a user to log in to a new group.

v newusers (8) - Update and create new users in batch form.

v nologin (5) - Prevent non-root users from logging onto the system.

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 137: MSIT 3A

v passwd (1) - Used to update a user’s password. The command “passwd username” willset the password for the given user.

v pwconv (8) - Used to create the file /etc/shadow from the file /etc/passwd to convert toshadow passwords.

v pwunconv (8) - Uses the files /etc/passwd and /etc/shadow to create /etc/passwd, thendeletes /etc/shadow to convert from shadow passwords.

v su (1) - run a shell with substitute user and group IDs

v useradd (8) - Create a new user or update default new user information

v userdel (8) - Delete a user account and their files from the system. The command “userdel-r newuser” will remove the user and deletes their home directory.

v usermod (8) - Modify a user account.

Other useful commands/examples

find / -user username -ls Gives a list of all files owned by username.chown -R myuser /home/myuser Changes ownership of all files in mysuer home

directory to myuser.

chmod +s filename SETS THE UID

7.5 USER REFERENCE FILESv /etc/passwd - Where the user’s name, and other pertinent information are stored. This includes

the password unless your system is using shadow passwords.

v /etc/shadow - Where the user’s password is stored if you are using shadow passwords.

v /etc/group - Where group names are stored.

v /etc/aliases - Where the user’s name is matched to a nickname for e-mail.

v /etc/sudoers - A list of users with special privileges along with the commands they canexecute.

7.6 USER MODIFICATIONSØ To add a user, while logged in as root, type “adduser username”.

Ø To set a user password, while logged in as root or the user that will be changed, type “passwdusername”. If “passwd” is typed, the password will be changed for the user, you are loggedin as.

Chapter 7 - System Administration138

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 138: MSIT 3A

Ø To remove a user, while logged in as root, type “userdel -r username”. This will remove theuser’s home directory. You can delete the user without the “-r” option and delete the user’shome directory manually. If the group the user was in, is no longer needed, you may delete itby editing the “/etc/group” file.

Ø The file “/etc/aliases” is where the user’s real name is matched to their user name for e-mailaccounts. Add users to this file in the form:

Firstname,Lastname:username

Then update the database by typing “newaliases”.

7.7 EXAMPLES OF MAKING CHANGES TO PERMISSIONSchmod u+x myfile Gives the user execute permission on myfile.

chmod +x myfile Gives everyone execute permission on myfile.

chmod ugo+x myfile Same as the above command, but specifically specifies user, group andother.

chmod 400 myfile Gives the user read permission, and removes all other permission. Thesepermissions are specified in octal, the first char is for the user, second forthe group and the third is for other. The high bit (4) is for read access, themiddle bit (2) os for write access, and the low bit (1) is for execute access.

chmod 764 myfile Gives user full access, group read and write access, and other readaccess.

chmod 751 myfile Gives user full access, group read and execute permission, and other,execute permission.

chmod +s myfile Set the setuid bit.

chmod go=rx myfile Remove read and execute permissions for the group and other.

Below are examples of making changes to owner and group:

chown mark test1 Changes the owner of the file test1 to the user Mark.

chgrp mark test1 Changes the file test1 to belong to the group “mark”.

MSIT 3A Linux Internals 139

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 139: MSIT 3A

7.8 SOME ADMINISTRATION COMMANDSØ su

(=substitute user id) Assume the superuser (=root) identity (you will be prompted for the password).Type “exit” to return you to your previous login. The root account is for administration and the su commandis to ease your access to the administration account when you require it.

Ø setup

(as root) Configure mouse, soundcard, keyboard, X-windows, and system services. There are manydistibution-specific configuration utilities, setup is the default on RedHat. Mandrake 7.0 offers very niceDrakConf.

Ø linuxconf

(as root, either in text mode or in the X terminal). You can access and change hundreds of networkssetting from here. ReadHats network configuration utility netconf is a subset of linuxconf, therefore it issimpler and sometimes easier to use.

Ø mouseconf

(as root). Simple tool to configure your mouse (after the initial installation). Mandrake includes also analternative mousedrake.

Ø kudzu

(as root). Automatically determines and configures your hardware. If having mysterious problemswith your mouse (or other serial hardware), you may want to disable kudzu, so it does not run on thesystem startup. You can run it manually when you need it.

Ø timeconfig

(as root) Set the timezone for your system. It is important to keep the timezone correct.

Ø setclock

(as root). Set your computer hardware clock from the current linux system time. Use the command“date” first to set up the linux system time. E.g., We could change the date and time to 2005-12-31 23:57using this command: date 123123572005.

Ø dateconfig&

(in X-terminal, as root else you will be asked for the root password). An excellent GUI utility to set ouroperating system and hardware clock and timezone, and tell our BIOS to keep time in UTC. We ignorethe previous two commands.

Chapter 7 - System Administration140

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 140: MSIT 3A

Ø xvidtune

(in X-terminal). Adjust the settings for your monitor display for all resolutions so as to eliminate blackbands, shift the display right/left/up/down, etc. (First use the knobs on your monitor to fit your text modecorrectly on the screen). Then use xvidtune to adjust the monitor frequencies for each resolution so it fitswell in your screen. To make the changes permanent, display the frequencies on the screen and thentransfer them to the setup file /etc/X11/XF86Config. On newer monitors, you may really prefer to adjustyour monitor using the built-in monitor settings—xvidtune is for older monitors which do not have thecapability to remember their settings.

Ø SuperProbe

(as root). A utility to determine the type of the video card and the amount of its memory.

Ø lspci

Show info on your motherboard and what cards are inserted into the pci extension slots. Our oldercomputer has ISA slots (or EISA) slots, no pci.

Ø lsdev

Display info about your hardware (DMA, IRQ, IO ports).

Ø chkconfig —list | more

To check the current status of services, We may use:

Ø service —status-all

To start a service right now, We may use something like (starts an proxy server):service squid startTo re-start samba networking, We may use:service smb restart

Ø fsck -t ext2 /dev/hda2

(=file system check, as root) Check and repair a filesystem, e.g., after an “unclean” shutdown due toa power failure. The above example performs the check on the partition hda2, filesystem type ext2. Youdefinitely want to unmount the partitions or boot Linux in the “single mode” to perform this (type “linuxsingle” at the LILO prompt or use init 1 as root to enter the single user mode). If errors are found duringthe filesystem checkup, We accept the defaults for repair. The problems with “unclean shutdown” can beavoided if you use a journalizing file system (e.g., ext3) on your system (highly recommended).

Ø mkbootdisk —device /dev/fd0 2.4.2-3

Make an emergency boot floppy. You are typically asked if you would like to make a boot disk duringthe system installation. The above command shows how to make it after install, on the first floppy drive (/dev/fd0). Your kernel name (needed in the command, here 2.4.2-3) can be determined either by runninguname -a or ls /lib/modules.

MSIT 3A Linux Internals 141

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 141: MSIT 3A

7.9 SUMMARYØ All access to a Linux system is through a user account. Every user must be set up by the

system administrator, with the sole exception of the root account (and some system accountsthat users seldom, if ever, use).

Ø While many Linux systems only have one user, that user should not use the root account fordailyaccess. Most systems allow several users to gain access, either through multiple userson the main console, through a modem or network, or over hard-wired terminals.

Ø Knowing how to set up and manage user accounts and their associated directories and filesis an important aspect of Linux system administration.

7.10 CHECK YOUR PROGRESS

I. ExercisesØ Work on all the commands described in the unit and also login as root in your system and

carry out the jobs of an System Administrator.

II. Choose appropriate answer1. For creating a new user account we require _______________.

a. create the account

b. provide an alias to their e-mail address

c. both a & b

d. none of the above

2. All Unix passwords, regardless of length (up to a maximum of 8 characters), are stored in thepassword file as encrypted strings of _________.

a. 13 characters

b. 16 characters

c. 8 characters

3. user account is removed using ________ command.

a. rm

b. userdelete

Chapter 7 - System Administration142

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 142: MSIT 3A

c. userdel

4. Unix systems keeps user account information, including one-way encrypted passwords, in a textfile called ________.

a. /etc/password

b. /etc/passwd

c. /etc/pwd

5. The /etc/shadow file contents are read _____________.

a. only by the current account

b. only by the root account

c. both a & b

6. df command gives the information about ______ space.

a. free space

b. used space

c. none of the above

7. The “/” file-system, mounted on /dev/hda1, contains the_____.

a. Linux kernel

b. device drivers

c. Other directories

d. All of the above.

III. Say True or False1. Passwd command is used for changing the password. True/False

2. The “root” account has security restrictions. True/False

3. The username is at atleast 8 characters long. True/False

4. Change the password using “su” command. True/False

MSIT 3A Linux Internals 143

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 143: MSIT 3A

IV. Essay type Questions1. Explain the different steps of creating user account.

2. Describe the total responsibility of a system administrator.

3. Write a note on the following.

i. disabling user accounts

ii. removing user accounts

iii. changing user passwords

iv. starting & stopping processes

4. Elaborate the commands used for system administration.

5. Explain the technique of managing /etc/passwd and /etc/group files.

6. Explain the technique of managing and changing permissions using atleast two commands.

V. Further readings and other activities1. Get more information using man or info or any help command for sh, bash, csh, ksh, inode, fs, env,

set, mount, mknd, id, dev, stat.

2. For further readings you can refer the following books

Ø Title: Linux internals Auihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.geocities.com/raomvp/doc/linux/linuxbook.htmlA complete reference for you to get more information.You can also extract solutions for exercises.

Ø More information on filesystem can be obtained from text book title: Introduction to the Shell programming

Author: Yashwanth Kanetkar

VI. Solutions

I. Choose appropriate answer1.c 2.a 3.c 4.b 5.b 6.a 7.d

II. Say True or False

1.true 2.false 3.false 4.false

Chapter 7 - System Administration144

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 144: MSIT 3A

Chapter 8

Editors and Tools

8.0 INTRODUCTION AND OBJECTIVES

There are many text editors available for the Linux system. Two of the most popular are vi (whichis actually an alias to the elvis editor) and emacs. Both provide basic editing functions such asinserting and deleting text, reading and writing of external files, text searching, and copying and

moving text.

vi is a full-screen editor that has two modes: command mode and text mode. emacs is an extendibleand powerful editor that is highly configurable to suit a variety of editing tasks (such as programming,document writing, and changing user or system files).

ObjectivesAt the end of this unit, You would be able to understand and expertise the following concets.

ð Linux VI editor

ð The emacs editor

ð System and network configuration commands

ð X Configuration utilities

ð Library and kernel dependency management tools

ð General Diagnostic function calls

ð To remotely use Xwindows from Ms Windows

ð Network application commands

MSIT 3A Linux Internals 145

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 145: MSIT 3A

8.1 LINUX VI EDITORØ vi is a visual editor. It is also called as the king of all editors.

Ø The following is a summary of the more essential commands of vi. You should consult the viman page for more details on the many other vi commands.

Ø A SUMMARY OF COMMANDS

i insert mode, (ESC to exit insert mode) allows text to be entered on the screen

a Append to right mode

/word Move to the occurrence of “word”

n Locate the next occurance

w Advance to the next word

e Advance to the next end of a word

b Move to the previous word

3b Move backward 3 words

dd delete line

3dd delete 3 lines

D Delete remainder of a line

dw Delete word

x Delete character

o Open space for new line below the cursor line

O Open a line above the cursor

CTRL-w Move back a word in append mode

u Undo last

U Undo all changes to current line

. In command mode, repeat the last text changing the command on thecurrent line

:w newfilename save the file to newfilename from the command mode

:wq save and quit

:q! quit without saving

Chapter 8 - Editor and Tools146

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 146: MSIT 3A

r replace then typa a character ot be replaced with r then return to break up a line

J join 2 lines

s substitute (sentence) typed text over a character, ESC when done

cw change word

c change part of a line from the cursor to the end of the line

cc substitute new text for aline, ESC when done

h move the cursor back one space

H move the cursor to the highest line on the screen

L move the cursor to the lowest line on the screen

M position the cursor at the midpoint on the screen

G last line in the file

0 (zero) Move the cursor to the beginning of the line it is on

view filename Open a file for viewing only

set number Turn on line numbers

set nonumber Turn off line numbers

Ø Options:

number

autoindent (ai) ctrl-d to move to the left

showmatch match brackets and parenthesis

tabstop=4

wrapmargine(wm) when line is wrapped (80-value)

:2 copy 4 Place a copy of line 2 after line 4.

:1,4 copy 7 (lines 1-4)

:n Access the next file for editing

MSIT 3A Linux Internals 147

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 147: MSIT 3A

8.2 THE EMACS EDITORØ emacs has become the editor of choice for many users because of its online help facility and

its extensive collection of editing commands. emacs is advanced and sophisticated text editor.For programmers, emacs is especially attractive because it can be configured to formatsource code for a variety of languages such as C, C++, and Lisp. emacs is somewhat easierto learn than vi, but it also features a much larger set of commands.

Ø There are likely 3 versions of emacs installed on your system: (1) text-only: type emacs in atext (not X-windows) terminal (2) graphical-mode: type emacs in an X-windows terminaland (3) X-windows mode: type “xemacs” in an X-windows terminal.

Ø STARTING EMACS

Ø emacs is invoked from the command line by entering emacs.

Ø To start emacs with a file to be edited, enter emacs filename.

Ø If you start emacs with a file, the screen will display the contents starting from the first line.Note the two lines at the bottom of the screen. The first of these lines, known as the modeline, displays the name of the file being edited and which part of the file that you are lookingat (for example, TOP, 20%, BOT). The last line on the screen is the echo line, which emacsuses to display system messages and as a prompt for more input.

Ø A SUMMARY OF COMMANDS

Ø The following table is a summary of the strictly essential commands that you will need forbasic editing in emacs. The emacs man page should be consulted for a more comprehensivedescription of the full emacs command set.

Ø Files are loaded into the following types of buffers:

• Fundamental - For text files

• C mode

• Shell mode

Ctrl v move forward a page

Alt v move back a page

Ctrl a move cursor to beginning of the current line

Ctrl e move cursor to the end of the current line

Ctrl h Get a list of help options, Ctrl h again describes what they are. Ctrl h, then t -tutorial, i -info reader

Chapter 8 - Editor and Tools148

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 148: MSIT 3A

Ctrl a,Ctrl space Set the mark

Ctrl w Deletes the text in the region (between the mark and the cursor)

Ctrl y Paste the text in the buffer at the current cursor location

Alt w Copy the text in the region

Ctrl k kill text

Alt y Replace yanked text with the previous block from the kill ring.(the ring ofbuffers where deleted and copied text is stored)

Ctrl x x a Copy the region into register a

Ctrl s Search for text

Ctrl r Search backward

Alt Ctrl s Search for something like jo.*n matching john, joan, etc

Alt % replace a string, space to replace, delete to skip, period to stop.

Alt x string replace all the string without prompts

Ø Ctrl x - make the following commands available (also allows macros):

Ctrx x ...commands... Ctrlx (Ctrl x e - to perform the macro)

Ctrl c Exit the editor

Ctrl s Save the current file

Ctrl f Find another file to edit

b Switch to another buffer

Ctrl b Present a list of available buffers

o Switch between two windows

C-b Moves back one character.

C-d Deletes the current character.

C-f Moves forward one character.

C-g Cancels the current command.

C-h Enters emacs online help.

C-n Moves forward to the next line.

MSIT 3A Linux Internals 149

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 149: MSIT 3A

C-p Moves back to the previous line.

C-s Searches forward for a string.

C-v Scrolls forward one screen.

M-v Scrolls backward one screen.

C-x u Undoes the last edit.

C-x C-c Exits emacs.

C-x C-s Saves the buffer to a file.

8.3 SYSTEM AND NETWORK CONFIGURATIONv linuxconf - A GUI interactive interface available on Redhat 6.0 or later which includes

netconf configuration.

v netconf - A GUI interactive interface available on Redhat 6.0 and later.

v kbdconf - A Redhat Linux tool which configures the /etc/sysconfig/keyboard file whichspecifies the location of the keyboard map file. This is a GUI based tool.

v mouseconfig - A Redhat Linux tool used to configure the /etc/sysconfig.mouse file. This is aGUI tool.

v timeconfig - A Redhat Linux tool used to configure the /etc/sysconfig/clock file. This is aGUI tool used to set timezone and whether or not the clock is set to GMT time.

v kernelcfg - A Redhat kernel configuration utility to be started from X.

v stty - Used to configure and print the console devices.

v setterm - Set terminal attributes.

v vmstat - Report statistics on virtual memory.

8.4 X CONFIGURATIONv XF86Setup - A newer X configuration program with a GUI interface which modifies the “/

etc/X11/XF86Config” configuration file.

v xf86config - An older X configuration program with a text based interface. It also modifiesthe “/etc/X11/XF86Config” configuration file.

Chapter 8 - Editor and Tools150

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 150: MSIT 3A

v Xconfigurator - The Redhat tool used during system setup to configure X.

v SuperProbe - A program that probes the video card to determine its type for usewith setting up X.

v xvidtune - This program will test video modes on the fly without modification to your Xconfiguration. Read the usr/X11R6/lib/X11/doc/VideoModes.doc file before running thisprogram.

8.5 LIBRARY AND KERNEL DEPENDENCY MANAGEMENTØ Library management:

v ldd - Used to determine shared libraries used by binary files. Type “ldd /bin/ls” to see theshared libraries used by the “ls” command.

v ldconfig - Used to update links and cache for system use of the most recent runtimeshared libraries.

Ø Kernel Management:

v lsmod - List currently installed kernel modules.

v depmod - Creates a dependency file, “modules.dep” in the directory “/lib/modules/x.x.x”,later used by modprobe to automatically load the relevant modules.

v insmod - Installs a loadable kernel module into the running kernel.

v rmmod - Unloads modules, Ex: rmmod ftape

v modprobe - Used to load a module or set of modules. Loads all modules specified in thefile “modules.dep”.

8.6 GENERAL DIAGNOSTICØ System resources

v free - Show system memory availability and usage

v df - Show the amount of disk free space on each mounted filesystem.

v du - Show disk usage

v lspci - List PCI devices

v pnpdump - Lists ISA PNP device resource information.

v vmstat - Reports virtual memory statistics.

MSIT 3A Linux Internals 151

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 151: MSIT 3A

Ø Other:

v env - List the current environment variables.

v printenv - Print a copy of the environment.

v set - Shows how the environment is set up. This command can be very useful whendebugging the environment.

v runlevel - List the current and previous runlevel.

v uname - Print system information. In my case, it prints “Linux”.

v dmesg - Show the last kernel messages printed during the last boot.

8.7 TO REMOTELY USE XWINDOWS FROM MS WINDOWSØ This section describes how to set this up for the MI/X server program to run on windows.

We have not been able to get this server to run with KDE or gnome, and many graphicimages do not seem to work with it. See the section on using X remotely for a better solution.This section is still here for anyone who wants to experiment with it.

v Get a copy of an X windows server program for windows such as MI/X for windowsfrom MicroImages at http://www.microimages.com.

v Install the package according to instructions on your windows box.

v Set up a shortcut to MI/X to run XS.EXE on the windows box.

v Invoke the shortcut to begin the Xwindows server program.

v Telnet to your linux box from your windows box

v Type “fvwm –display mark:0 &” where “mark” is the name of your windows box

Ø Tips

v To exit X windows quickly or if the video is working improperly, use the<CTRL><ALT><BACKSPACE> key combination.

v To increase or decrease graphic mode use <CTRL><ALT><+> or <-> respectively. Thiswill toggle through video modes on the modes line in the screen section of the XF86Configfile.

v The command “X -showconfig” lists the video chip names known to the X server.

Chapter 8 - Editor and Tools152

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 152: MSIT 3A

v The command “X -probeonly > /tmp/test.out 2>&1” lists supported chipsets and otheruseful information.

v The command “X > /tmp/test.out 2>&1” runs X bare. Use Ctrl-Alt-BS key combination,then examine the contents of the output file to help debug X startup problems.

8.8 NETWORK APPLICATION COMMANDS Ø lynx file.html

View an html file or browse the net from the text mode. Although lynx’s look or convenience of use isnot as great as GUI-based browser, it is light-weight, almost always works, and does not require anyconfiguration, as long as your networks is functional.

Ø konqueror &

(in X terminal) File manager and web browser in one. Very nice, in many very comptetitive to mozilla.Comes with KDE.

Ø pine

A good, old-fashioned, text-mode mail reader. Another old-fashioned and standard one is elm. Yourmozilla mail will read the mail from your Internet account. pine will let you read the “local” mail, e.g. themail your son or a cron process sends to you from a computer on your home network. The command mailcould also be used for reading/composing mail, but it would be inconvenient—it is meant to be used inscripts for automation.

Ø mutt

A really basic but extremally useful and fast mail reader.

Ø mail

A basic operating system tool for e-mail. Look at the previous commands for a better e-mail reader.mail is good if you wanted to send an e-mail from a shell script.

Ø kmail &

(in X-terminal) Nice, GUI mail program. We use kmail, it is much better than netscape mail. We canhave multiple accounts and retrieve mail from the smtp (local) server and pop3 servers (internet serviceprovider) to the same mailbox. Simple and elegant. Supports digital signatures.

Ø licq &

(in X terminal) An icq “instant messaging” client. Another good one is kxicq. Older distributions don’thave an icq client installed, you may have to do download one and install it.

MSIT 3A Linux Internals 153

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 153: MSIT 3A

Ø talk username1

Talk to another user currently logged on your machine (or use “talkusername1@machinename” totalk to a user on a different computer) . To accept the invitation to the conversation, type the command“talk username2”. If somebody is trying to talk to you and it disrupts your work, your may use thecommand “mesg n” to refuse accepting messages. You may want to use “who” or “rwho” to determinethe users who are currently logged-in. talk is one of the old-fashioned “standard” UNIX tools, yet it stillcan be cool and useful in some situations.

Ø telnet server

Connect to another machine using the TELNET protocol. Use a remote machine name or IP address.You will be prompted for your login name and password—you must have an account on the remotemachine to login. Telnet will connect you to another machine and let you operate on it as if you weresitting at its keyboard (almost). Telnet is not very secure—everything you type moves through the networksin open text, even your password! A competent system administrator on a computer “on-route” can readwhat you type. Use ssh (requires some setup) for encrypted transmission.

Ø ftp server

Ftp another machine. (There is also ncftp which adds extra features and gftp for GUI .) Ftp is good forcopying files to/from a remote machine. Try user “anonymous” if you don’t have an account on theremote server. After connection, use “?” to see the list of available ftp commands. The essential ftpcommands are: ls (see the files on the remote system), ASCII,binary (set the file transfer mode to eithertext or binary, important that you select the proper one ), get (copy a file from the remote system to thelocal system), mget (get many files at once), put (copy a file from the local system to the remote system),mput (put many files at once), bye (disconnect). For automation in a script, you may want to use ncftpputand ncftpget, for example:

8.9 SUMMARYØ There are many other editors also present.

Ø pico filename

Edit a text file using the simple and standard text editor called pico. Use <Ctrl>x to exit. Thereare many text editors for Linux, including several GUI-based. A brand new clone of pico (GPLed)is nano.

Ø kwrite

(in X terminal) Very nice, “advanced text editor”. Supports vertical text selection!

Chapter 8 - Editor and Tools154

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 154: MSIT 3A

Ø kate, kedit, gedit

(in X terminal). Simple yet nice text editors (GUI based).

Ø gxedit

(in X terminal) Another multi-purpose, feature packed text editor. This one even has timed backup.

Ø latte

(in X terminal) “Code” editor, i.e., plain text editor meant for writing programs.

Ø nedit

(in X terminal) Another programmer editor. Very nice and loaded.

Ø bluefish

(in X terminal) html editor (source with syntax highlighting and many tools and options).

8.10 CHECK YOUR PROGRESS

I. ExercisesØ Work on all the commands described in the unit and also login as root in your system and carry

out the jobs of an Network Administrator and have a hands-on experience with all editors.

II. Choose the correct answer1. Linux uses _______ slash.

a. Normal

b. Back

c. Double

d. None of the above

2. The following are the Linux commands _____

a. ATTRIB

b. BACKUP

c. RESTORE

d. None of the above

MSIT 3A Linux Internals 155

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 155: MSIT 3A

3. The equivalent for COPY in Linux is _____

a. mv & rm

b. cp

c. both a & b

d. none of the above.

4. The example if an editor is _____.

a. vi

b. emacs

c. ex & ed

d. all of the above.

II. Say True or False 1. In Linux operating system filenames are limited to 8 characters. True/False

2. Linux operating system is case sensitive. True/False

3. ifconfig is used for netwoks ip address setting. True/False

4. free - Show system memory availability and usage True/False

III. Essay type questions1. List out the comparisons between DOS-to-LINUX.

2. Explian different modes of vi-editor and describe emacs editor.

3. Describe the network configuration commands.

4. Explain the X Configuration utilities

5. Explain the Network application commands

6. Describe how to remotely use Xwindows from Ms Windows.

IV. Further readings and other activities1. Get more information using help commands aboutVi, ed, red, gEdit, vim, Emacs, ex, sed,

awk, mtools

Chapter 8 - Editor and Tools156

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 156: MSIT 3A

2. Install from Linux source cd, The dos emulation package by name DOSEMU and work on all dosemulation commands.

3. For further readings you can refer the following booksTitle: Linux internalsAuihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.geocities.com/raomvp/doc/linux/linuxbook.htmlA complete reference for you to get more information.

You can also extract solutions for exercises.

Ø Title: Power Tools, second edition,

Author: Jerry Peek, Tim O’Reilly, Mike Loukides, and others; O’Reilly & Associates; ISBN 1-56592-260-3; 1997. A huge collection of tips, techniques, and concepts for making intermediateusers into advanced users.

Ø Title: Learning the vi EditorAuthor: Linda Lamb; O’Reilly & Associates; ISBN 0-937175-67-6;1992. A complete introduction to vi, structured like LINUX in a Nutshell.

VI. Solutions

I. Choose the correct answer 1.a 2.d 3.a 4.d

II. Say True or False 1.False 2.True 3.True 4.True

MSIT 3A Linux Internals 157

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 157: MSIT 3A

Chapter 9

Installation of Linux

9.0 INTRODUCTION AND OBJECTIVES

We have prepared and structured this chapter in a manner that follows the original installation ofthe Red Hat Linux operating system from CD-ROM. Each section below refers to, and willguide you through, the different screens that appear during the setup of your system after

booting from the Red Hat boot diskette. We promise that it will be interesting to have the machine youwant to install Linux on ready and near you when you follow the steps described below.

You will see that through the beginning of the installation of Linux, there are many options, parameters,and hacks that you can set before the system logs in for the first time.

Unlike some versions of Linux, Red Hat gives you a number of methods of installing its operatingsystem that offer versatility and ease of use. For most people, installation will be a very simple task withmost of the process automated by the Red Hat installation routines. Users with some special hardware ordisk-layout problems will have to perform a more typical manual installation of Linux. This chapter coversall the steps you need to install Linux manually, as well as the brief instructions you need to allow anautomated installation.

If you want to try an automated installation of Red Hat Linux, there are two ways to go. One is calledfloppyless, as it uses a routine on the CD-ROM to install itself. This step simply saves you the trouble ofmaking floppy diskettes; the rest of the installation process is exactly the same.

The alternative to floppyless installation is to create boot and root floppies and use those to start up thesystem and access the CD-ROM. The following sections discuss both floppyless and floppy-based methodsin more detail.

Chapter 9 - Installation of Linux158

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 158: MSIT 3A

OBJECTIVESAt the end of this unit, You would be able to install and configure the Linux operating system and know

and expertise the following concepts of system installation.

ð Devices of installation

ð Partitioning hard disk

ð Partition sizes

ð Mount points

ð Mounting partitions at startup

ð The fstab file

ð Know your hardware

ð Creating the Linux boot disk

ð Making a bootable diskette under MS-DOS

ð Making a diskette under a Linux-Like OS

ð Beginning the installation of Linux

ð Installation options - class and method

ð Manual configurations

ð Package installations

ð Standard linux partition filesystem types

ð Network administration tools

9.1 DEVICES OF INSTALLATIONThe first partition on a IDE hard drive is called partition 1, and is called /dev/hda1 if the drive is the

primary IDE master.

/dev/fd0 First Floppy disk [fd1 = Second]

/dev/hda1 IDE Hard drive 1, partition 1

/dev/hdb3 IDE Hard drive 2, partition 3

/dev/sda1 First SCSI interface (fast hard drive), device id 1

MSIT 3A Linux Internals 159

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 159: MSIT 3A

/dev/sdc3 First SCSI interface, device id 3

/dev/cdrom CD ROM drive

/dev/mouse Mouse device, sometimes a pointer to another device such as /dev/psaux, a ps/2 mousedriver.

primary IDE master /dev/had

primary IDE slave /dev/hdb

secondary IDE master /dev/hdc

secondary IDE slave /dev/hdd

9.2 PARTITIONING HARD DISKØ This is the most important work for installation of Linux. Many distributions use disk, cfdisk, or

disk druid to set up partitions for Linux. You will need a Linux swap partition and at least 1 Linuxnative partition. You can install Linux with other operating systems such as DOS, windows95, 98,and/or NT/Win2000. If you will install with NT or Windows 2000, you must use extra care sinceNT’s boot loader may conflict with LILO, the boot loader used by Linux. We have installed Linuxwith Windows98, and Windows 2000. What we recommend is setting your partitions in advanceby using partition magic 4.0 [partitioning utility]. If you can’t do it this way use fdisk, then youmay have to format any non-Linux drives with the appropriate programs.

9.3 PARTITION SIZESØ Swap partition

The swap partition, we usually make 128Mb. The recommendation is that the swap partition betwice as large as RAM memory or greater. In the past Linux could not use swap partitions largerthan 128MB but the size limitation depends on your system’s architecture. On most Intel based systems,a swap partition of up to 2GB [2048MB] can be used. You can also make multiple swap partitions.

Ø Native Partition(s)

If you are setting up a computer you will be learning Linux on or installing several operating systems,you may want one Linux native partition [3 to 5 GB total] per Linux install. If, however, you are setting upa dedicated high performance server, you may want to set up several Linux native partitions and installvarious parts of the operating system on separate ones similar to the following recommendation or somemodification thereof:

Chapter 9 - Installation of Linux160

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 160: MSIT 3A

1. / - Root size of 200MB.

2. /usr - Holds local software. Minimum of 700MB, Recommended 1.7 GB or more.

3. /var - Holds mail, spool, and log files. Recommended size of 400MB

4. /home -The rest of the disk, Used for user storage and in a multi user system, is where mostdata will be stored.

Ø In systems that we will use at home or learn on, We normally use one linux native partition perLinux install. If we are installing Redhat and Slackware we might make two 3GB partitions. Welike to make the size of our Linux native [ext2] partitions about 3GB depending on the amount ofhard drive space we have and the number of systems we are installing. This is because Linuxtakes about 0.8G to 1.3G for a full install and some room is left over for expansion.

Ø If installing only one Linux system, we like to have 4-6GB. One thing we like to do when installinga system to be shared with Windows, which can make life convenient and save your data, is tomake a large partition on a large hard drive that is FAT32. Since Linux can mount this and mostif not all Windows operating systems can see this, your data can be available in a commonfilesystem on this partition.

9.4 MOUNT POINTSØ A mount point is a directory which a device or partition is attached to. During your install you may

need to choose mount points for specific filesystems.

Ø You will need to set the mountpoint of “/” for your root filesystem on the disk partitionyou are installing your system to. For example if you are installing your system on the secondpartition of an IDE drive, you will select the “/dev/hda2” drive mount point to be “/”.

Ø If you want to mount other drives or partitions, you may, for example, mount your second harddrive or partition to a directory called “/data”. Once your install is complete you will need to besure this mount point exists and possibly create it with the “mkdir /data” command. Then the nexttime you boot your system, this partition should be available for use (or you can use the command“mount -a” to mount all filesystems in the /etc/fstab file.

9.5 MOUNTING PARTITIONS AT STARTUPØ To mount other partitions at startup modify the “/etc/fstab” file. Each line in the file refers to a

different filesystem. Fields are separated by whitespace. The primary filesystems must be mountedfirst, so they must be in correct order. Your native partition for the system you are running shouldbe listed first. The fields are as follows:

MSIT 3A Linux Internals 161

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 161: MSIT 3A

Ø The name of the device such as “/dev/hda1”

Ø The mount point. Use “/” for root. Other typical mount points are “/dos” for DOS, “swap” ornone” for the swap partition, and “/mnt/floppy” for “/dev/fd0” (the floppy drive).

Ø The type of filesystem. They are: mini, ext, ext2(linux native), xiafs, msdos, hpfs, ntfs,fat32, iso9660(CD-ROM), nfs, swap (for swap space).

Ø The mount options for use with the filesystem. Each filesystem type has different mount options.Read the mount man page to see possible options. ro= read only, user- allows normal users tomount the device.

Ø The frequency the filesystem needs to be dumped (backed up) by the dump command. For ext2,normally make it 1, for others make it 0. 0 or nothing means it is not dumped. If 1, it is backed upduring a system backup.

Ø A number telling the order in which the filesystems should be checked at reboot time by the fsckprogram. Your root should be 1, others are in ascending order or 0 to not be checked.

Ø To determine your hard drive’s partitions and see what each partition holds which operatingsystem, you may use the fdisk program. Use p option to see a list of current partitions, then youcan add them to your fstab file.

9.6 THE FSTAB FILEØ A typical /etc/fstab file:

/dev/hda2 / ext2 defaults 1 1/dev/hdb1 /data auto defaults 0 0/dev/hda1 /dos vfat defaults 0 0/dev/hda3 /slackw ext2 defaults 0 0/dev/hda4 swap swap defaults 0 0/dev/cdrom /mnt/cdrom iso9660 noauto,owner,ro 0 0/dev/fd0 /mnt/floppy ext2 noauto,owner 0 0none /proc proc defaults 0 0none /dev/pts devpts gid=5,mode=620 0 0

Ø These are the options:

v defaults - Use the default options of rw, suid, dev,exec,auto, nouser, and async.

v auto - Auto detect the type of filesystem.

Chapter 9 - Installation of Linux162

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 162: MSIT 3A

v noauto - The -a option will not mount the filesystem.

v owner

v ro - Read only

v rw - Read and write allowed

v user - Users have permission to mount this filesystem

v users - Allows a user to mount and another user to unmount the filesystem

Ø The /proc directory is required for tracking processes in memory (RAM). The directories /data,/dos, and /slackw in this example must exist or their mounts will fail.

9.7 KNOW YOUR HARDWAREØ Understanding the hardware of your computer is essential for a successful installation of Linux.

Therefore, you should take a moment and familiarize yourself with your computer hardware. Beprepared to answer the following questions:

v How many hard drives do you have?

v What size is each hard drive (eg, 15GB)?

v If you have more than one hard drive, which is the primary one?

v What kind of hard drive do you have (eg, IDE ATA/66, SCSI)?

v How much RAM do you have (eg, 256MB RAM)?

v Do you have a SCSI adapter? If so, who made it and what model is it?

v Do you have a RAID system? If so, who made it and what model is it?

v What type of mouse do you have (eg, PS/2, Microsoft, Logitech)?

v How many buttons does your mouse have (2/3)?

v If you have a serial mouse, what COM port is it connected to (eg, COM1)?

v What is the make and model of your video card? How much video RAM do you have (eg,8MB)?

v What kind of monitor do you have (make and model)?

v Will you be connected to a network? If so, what will be the details of following entities.

MSIT 3A Linux Internals 163

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 163: MSIT 3A

* IP address * netmask * gateway address * domain name server’s IP address

* domain name * hostname * types of network(s) card(s) (makes and model)

* number of card(s) (makes and model).

9.8 CREATING THE LINUX BOOT DISKØ The first thing to do is to create an installation diskette, also known as a boot disk. If you have

purchased the official Red Hat Linux CD-ROM, you will find a floppy disk named “Boot Diskette”in the Red Hat Linux box so you don’t need to create it. Sometimes, you may find that theinstallation will fail using the standard diskette image that comes with the official Red Hat LinuxCD-ROM. If this happens, a revised diskette is required in order for the installation to workproperly.

Ø There are two methods to create the installation Boot Disk, the first method is to use an existingicrosoft Windows computer and the second using an existing Linux computer.

9.9 MAKING A DISKETTE UNDER MS-DOSØ Before you make the boot disk, insert the Official Red Hat Linux CD-ROM Disk1 in your

computer that runs the Windows operating system. When the program asks for the filename,enter boot.img for the boot disk. To make the floppies under MS-DOS, you need to use thesecommands (assuming your CD-ROM is drive D: and contain the Official Red Hat Linux CD-ROM).

Ø Open the Command Prompt under Windows: Start | Programs | Command Prompt

C:\> d:

D:\> cd \dosutils

D:\DOSUTILS> RAWRITE

Enter disk image source file name: ..\images\boot.img

Enter target diskette drive: a:

Please insert a formatted diskette into drive A: and press -ENTER- :

D:\dosutils>

Ø The rawrite.exe program asks for the filename of the disk image: Enter boot.img and insert ablank floppy into drive A. It will then ask for a disk to write to: Enter a:, and when complete, labelthe disk “Red Hat boot disk”, for example.

Chapter 9 - Installation of Linux164

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 164: MSIT 3A

9.10 MAKING A DISKETTE UNDER A LINUX-LIKE OSØ To make a diskette under Linux or any other variant of Linux-Like operating system, you must

have permission to write to the device representing the floppy drive (known as /dev/fd0H1440under Linux).

Ø This permission is granted when you log in the system as the super-user “root”. Once you havelogged as “root”, insert a blank formatted diskette into the diskette drive of your computer withoutissuing a mount command on it. Now it’s time to mount the Red Hat Linux CD-ROM on Linuxand change to the directory containing the desired image file to create the boot disk.

Ø Insert a blank formatted diskette into the diskette drive.

Ø Insert the Red Hat Linux CD Part 1 into the CD-ROM drive.

[root@rao /]# mount /dev/cdrom /mnt/cdrom

[root@rao /]# cd /mnt/cdrom/images/

[root@rao images]# dd if=boot.img of=/dev/fd0H1440 bs=1440k

1+0 records in

1+0 records out

[root@rao images]# cd /

[root@rao /]# umount /mnt/cdrom

Don’t forget to label the diskette “Red Hat boot disk”.

9.11 BEGINNING THE INSTALLATION OF LINUXØ Now that we have made the boot disk, it is time to begin the installation of Linux. Since we’d start

the installation directly off the CD-ROM, boot with the boot disk. Insert the boot diskette youcreate into the drive A: on the computer where you want to install Linux and reboot the computer.

Ø At the boot: prompt, press Enter to continue booting and follow the three simple steps below:

Ø Step 1

The first step is to choose what language should be used during the installation process. In ourexample we choose the English language.

Ø Step 2

After that, the system allows you to choose your keyboard type, layout type for the keyboard, andthe possibility to enable or disable Dead Keys.

MSIT 3A Linux Internals 165

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 165: MSIT 3A

Ø Step 3

Finally, we choose the kind of mouse type we use and if this mouse has two or three buttons. Ifyou have a mouse with just two buttons, you can select the option named “Emulate 3 Buttons”and click both mouse buttons at the same time to act as the middle mouse button.

Ø Once we have completed the above three steps, we are ready to begin the installation of Red HatLinux.

9.12 INSTALLATION OPTIONS - CLASS AND METHODØ Red Hat Linux includes four different classes, or type of installation. They are:

v Workstation

v Server System

v Laptop

v Custom System

Ø The first two classes (Workstation, and Server System) give you the option of simplifying theinstallation process with a significant loss of configuration flexibility that we don’t want to lose.

9.13 MANUAL CONFIGURATIONSØ Now that we know exactly what partitions we need to create for our new Linux machine, it is

time to choose the partitioning software we will use to make these partitions on the machine.With Red Hat Linux two programs exist to assist you during this step. During setup, the installationwill give you two choices, which are:

ð Manually partition with Disk druid

ð Manually partition with fdisk [experts preferred]

Ø Disk Druid is the new software used by default in Red Hat Linux to partition your disk drive, thisis an easy to use program, which allows you to work through a graphical interface to create yourpartitions tables.

Ø fdisk was the first partitioning program available on Linux. It is more powerful then Disk Druidand allows you to create your partition table in exactly the way you want it (if you want to putyour swap partition near the beginning of your drive, then you will need to use fdisk).

Chapter 9 - Installation of Linux166

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 166: MSIT 3A

Ø On the next screen you will see the LILO Configuration screen. LILO, the LInux LOader, issoftware that can be used to start Linux on your computer. From this screen, you will see differentconfigurable options related to LILO.

Ø The first option is:- Create boot disk

The Create boot disk option is checked by default. If you do not want to create a boot disk, youshould deselect this option. Also, this option must be checked if you decide to not install LILO onthe MBR (the Master Boot Record) or if you are not installing LILO at all.

Ø The second option is:- Do not install LILO

This option allows you to skip installing LILO if you use a boot disk rather than LILO to start yoursystem.

Ø The third option (the one that we will chose) installs LILO in your Linux system and gives you thechoice to install LILO boot record on:

ð Master Boot Record (MBR)

ð First Sector of Boot Partition

Usually, if Linux is the only Operating System on your machine (and this must be the case ina custum installation), you should choose the “Master Boot Record (MBR)” option.

Ø Network Configuration

After that, you need to configure your network. If you have multiple Ethernet devices, eachdevice will have its own configuration screen.

Ø Firewall Configuration

The latest release of Red Hat Linux now offers the possibility to configure a Firewall duringinstallation. This is OK for the average end user but NOT for serious Firewall security. From thenext screen that appears, you will see three different security levels available, choose the “Nofirewall” option and click Next.

Ø Language Support Selection

From here the installation will ask you to choose the default language that will be used on yourLinux system.

Ø Time Zone Selection

On the next screen, you will have the opportunity to set your time zone. Once selected clickNext.

MSIT 3A Linux Internals 167

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 167: MSIT 3A

Ø Account Configuration

After the clock has been configured, you need to give your system a root password account.

Ø Authentication Configuration

Finally, the last stage is the authentication configuration. For Authentication Configuration don’tforget to select:

ð Enable MD5 passwords

ð Enable Shadow passwords

Enable MD5 passwords - allows a long password to be used (up to 256 characters), insteadof the Unix standard eight letters or less.

Enable shadow passwords - provides a very secure method of retaining passwords for you.All passwords are stored in a file named shadow, which is readable only by the super-userroot.

Enable NIS, LDAP, and Kerberos doesn’t need to be selected.

Ø Selecting Package Groups

After your partitions have been configured and selected for formatting and configurations havebeen set for your specific system, you are ready to select packages for installation. By default,continue by pressing next key till you get message linux is installed successfully.

9.14 PACKAGE INSTALLATIONSØ tar.gz SOURCE PACKAGE GENERAL INSTRUCTIONS

1 Read the install documentation associated with the installation

2 Put the packed file in the directory you want it to be installed under.

3 Examine the package with the command

“tar tvzpf <packagename>.tar.gz” to see where it will install.

4 Unpack the tar.gz file in one step with

“tar xvzpf <packagename>.tar.gz or in two steps with

“gunzip <packagename>.tar.gz” and

“tar xpf <packagename>.tar” It will create a directory like

Chapter 9 - Installation of Linux168

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 168: MSIT 3A

“packagename-2.3.4” and place the extracted information here.

5 Typically the following outlines the rest of the steps but they will vary from package topackage. Go into the created subdirectory and type “./configure”.

6 Type “make all” or “./make”

7 Type “make install” or “./make install”

Ø Installing Redhat Packages

Ø The RedHat package manager installation utility is called rpm. rpm is supposed to be an intelligentsoftware package manager.

rpm –help To get help

rpm -q mypack-1.0.1.rpm Queries the database of installed packages to see if thispackage is installed or what version of it is installed.

rpm –ivh mypack-1.0-1.rpm Installs mypack.

rpm –uvh mypack-2.0-1.rpm Upgrades mypack.

rpm –qip mypack-1.2.2.rpm To query with details about the package.

rpm –qlp mypack-1.2.2.rpm Gives a list of files this package installs.

rpm -e mypack-1.2.2 Removes the package mypack-1.2.2.

9.15 STANDARD LINUX PARTITION FILESYSTEM TYPESØ As a quick reference, here is a brief summary of the standard linux partition types (“filesystems”)

with a short description. [We can have a look at the source code files at /usr/src/linux/fs].

Ø minix

It is the filesystem used in the Minix operating system, the first to run under Linux. It has a number ofshortcomings: a 64MB partition size limit, short filenames, a single time stamp, etc. It remains useful forfloppies and RAM disks.

Ø ext

It is an elaborate extension of the minix filesystem. It has been completely superseded by the secondversion of the extended filesystem (ext2) and will eventually be removed from the kernel.

Ø ext2

It is the high performance disk filesystem used by Linux for fixed disks as well as removable media.The second extended filesystem was designed as an extension of the extended file system (ext). ext2

MSIT 3A Linux Internals 169

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 169: MSIT 3A

offers the best performance (in terms of speed and CPU usage) of the filesystems supported underLinux. In short, ext2 is the main (default, typical) Linux filesystem.

Ø ext3

It is an extension of the ext2 filesystem with journalizing. It is backward and forward compatible withext2. It means that ext2 can be converted into ext3 without reformatting or data loss (just re-mounting thepartition is required). ext3 can be changed back to ext2, also without data loss. It is highly recommendedthat you use this filesystem.

Ø xiafs

It was designed and implemented to be a stable, safe filesystem by extending the Minix filesystemcode. It provides the basic most requested features without undue complexity. The xia filesystem is nolonger actively developed or maintained. It is used infrequently.

Ø msdos

It is the filesystem used by DOS, Windows, and some OS/2 computers. msdos filenames can be nolonger than 8 characters followed by an optional period and 3 character extension.

Ø umsdos

It is an extended DOS filesystem used by Linux. It adds capability for long filenames, UID/GID,POSIX permissions, and special files (devices, named pipes, etc.) under the DOS filesystem, withoutsacrificing compatibility with DOS.

Ø vfat

It is an extended DOS filesystem used by Microsoft Windows95 and Windows NT. VFAT addscapability for long filenames under the MSDOS filesystem.

Ø proc

It is a pseudo-filesystem which is used as an interface to kernel data structures rather than reading andinterpreting /dev/kmem. In particular, its files do not take up disk space. See $ man 5 proc.

Ø iso9660

It is a CD-ROM filesystem type conforming to the ISO 9660 standard. Two extensions (listed below)are automatically supported.

v High Sierra —Linux supports High Sierra, the precursor to the ISO 9660 standard for CD-ROM filesystems. It is automatically recognized within the iso9660 filesystem support underLinux.

v Rock Ridge —Linux also supports the System Use Sharing Protocol records specified bythe Rock Ridge Interchange Protocol. They are used to further describe the files in the

Chapter 9 - Installation of Linux170

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 170: MSIT 3A

iso9660 filesystem to a UNIX host, and provide information such as long filenames, UID/GID, POSIX permissions, and devices. It is automatically recognized within the iso9660filesystem support under Linux.

Ø hpfs

It is the High Performance filesystem, used in OS/2. This filesystem is read-only under Linux due tothe lack of available documentation.

Ø sysv

It is an implementation of the System V / Coherent filesystem for Linux. It implements all of Xenix FS,System V / 386 FS, and Coherent FS.

Ø nfs

It is the network filesystem used to access disks located on remote computers.

Ø smb

It is a network filesystem that supports the SMB protocol, used by MS Windows for Workgroups,Windows NT, and Lan Manager. To use smb fs, you need a special mount program. Standard linuxcommand “smbmount” will do.

Ø ncpfs

It is a network filesystem that supports the NCP protocol, used by Novell NetWare.

Ø devpts

It is a pseudo file system, traditionally mounted on /dev/pts. In order to acquire a pseudo terminal, aprocess opens /dev/ptmx; the number of the pseudo terminal is then made available to the process and thepseudo terminal slave can be accessed as /dev/pts/<number>.

Ø fat

It is not a separate filesystem, but a common part of the msdos, umsdos and vfat filesystems.

Ø UFS

It is a file system widely used in different operating systems.

Ø swap

It is a special partition type used for swapping data from memory to hard drive.

Ø raiserfs

It is a brand new journalizing filesystem available as standard with Linux kernel version 2.4.1 up.

MSIT 3A Linux Internals 171

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 171: MSIT 3A

Ø hfs

(=hierarchical files system)—MacIntosh filesystem. It is a late beta version., i.e., not recommendedfor use with critical data, unless read-only.

Ø ntfs

MS Windows NT filesytem. It is still “experimental” under Linux, i.e. not recommended for productionmachines, unless read-only.

9.16 NETWORK ADMINISTRATION TOOLSØ netconf

(as root) A very good menu-driven setup for your network.

Ø ping machine_name

Check if you can contact another machine (give the machine’s name or IP), press <Ctrl>C when done(without <Ctrl>c, the command keeps going). As all Linux commands, ping has options, including the“ping of death” attack, when it seems you can ping some servers so they die—try the options -f and -s.

Ø host host_to_find, nslookup host_to_find, dig ip_to_find

(Three commands, use any.) Query your default domain name server (DNS) for an Internet name (orIP number) host_to_find. This way you can check if your DNS works. You can also find out the nameof the host of which you only know the IP number.

Ø traceroute host_to_trace

Have a look how your messages trace to host_to_trace (which is either a host name or IP number).

Ø mtr host_to_trace

(as root) A powerful and nice tool that combines the functionality of the older ping and traceroute.

Ø firewall-config

(as root, in Xterm). A GUI for building your custom firewall.

Ø ifconfig

(as root) Display info on the network interfaces currently active (ethernet, ppp, etc). Your first ethernetshould show up as eth0, second as eth1, etc, first ppp over modem as ppp0, second as ppp1, etc. The “lo”is the “loopback only” interface which should be always active. Use the options (see ifconfig —help) toconfigure the interfaces.

Chapter 9 - Installation of Linux172

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 172: MSIT 3A

Ø ifup interface_name

(/sbin/ifup to run as a user)

Startup a network interface. Example: ifup eth0, ifup ppp0, ifup ppp1

Users can start up or shutdown the ppp interface only when the permission is given in the ppp setup(using netconf ). To start a ppp interface (dial-up connection), We normally use kppp available under theKDE “K” menu (or by typing kppp in an X-terminal).

Ø /etc/rc.d/init.d/network restart

Restart the network using its normal initialization script (the same which is used during bootup). Usefulif you just have manually made changes to your network configuration. Any other service listed in init.dcan be stopped, started, or restarted in a similar way (call the script with an options stop, start or restart).

Ø ifdown interface_name

(/sbin/ifdown to run it as a user).

Shut down the network interface. Example: ifdown ppp0.

Ø netstat | more

Displays a lot information on the status of your network.

Ø /usr/sbin/mtr —gtk

(as root, in X windows if you wish the nice gtk-based interface). Network diagnostic tool combiningthe capabilities of traceroute and ping.

Ø nmap ip_number

Map the ports on the machine with ip_number. REALLY useful to establish the security of yournetwork configuration as you can see the opened ports.

Ø ethereal

(as root, in Xterminal) Network analyzer—view the network trafic going through your computer.

Ø tcpdump -i ppp0 -a -x

(as root) Print all the network traffic going through the first over-the-phone interface (ppp0) as asciiand hexadecimal.

MSIT 3A Linux Internals 173

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 173: MSIT 3A

9.17 SUMMARYØ The process of installing Red Hat Linux is straightforward, although there are lots of little

problems scattered throughout the process that can cause hassles. Red Hat Linux is mucheasier to install than many other versions of Linux, so you will find the installation goes quiteeasily. Common errors that you might make are handled nicely by the Red Hat installationprogram, and the system is versatile enough to handle most configuration requirements.

Ø The essential steps for installing Red Hat Linux are as follows:

1. Create boot and root disks.

2. Boot Linux from floppies.

3. Partition the hard disk.

4. Create a swap file.

5. Create a Linux file system.

6. Install the Linux software.

7. Configure the kernel.

8. Set the boot process.

9. Reboot into Linux from your hard disk.

Ø The process is similar whether you are installing from a CD-ROM or from a diskette. Becausethe CD-ROM is the most common form of installation, it is used as the example in thischapter.

Ø Much of this chapter will be familiar to you if you have installed Linux before, although someusers really don’t know what goes on during the automated installation script. Knowing theprocess, and staying on top of it, helps prevent problems with the Linux installation.

9.18 CHECK YOUR PROGRESS

I. ExercisesØ Work on all the installation commands described in the unit by logging in as root.

Ø Start installing a Redhat Linux. This is available with magazines such as pcquest.

Ø Make multiple partitions to install dual boot or triple boot of operating systems.

Chapter 9 - Installation of Linux174

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 174: MSIT 3A

Ø Try installing updation packages for the system you have installed.

Ø The student has to concentrate for Creation of an Installation Diskette, Partitioning HardDrive(s) and choosing Desired Packages required to Install, Multi-boot with Other OperatingSystems.

Ø Give an example of space works of partitions for installing Linux and windows operatingsystems in one hard disk size of 4.3 Gb. You may use 2 Gb for windows 98 operating system.

Ø Install first on a separate hard disk (min 300 MB) Linux OS in text mode only.

Ø Install the linux OS including X windows on a separate hard disk (min 1.2 GB).

Ø Install the linux OS including X windows on a hard disk (min 4.3 GB) with multi-boot conceptalong with windows 95/98 also windows NT.

Ø Try out creation of Linux boot diskette with different commands.

Ø Partition a hard disk with different sizes using any partition command such as diskdruid orfdisk.

II. Choose the correct answer1. Creation of linux boot disk can be done through

a. rawrite b. mkbootdisk c. diskcopy d. all of these.

2. The example of a compressed file used for any package installation is

a. *.tar.gz b. *.rpm c. *.zip d. all of these.

3. Linuxconf can be used to

a. mount a drive b. configure a network c. administer users d. all of these

4. LILO is used for

a. Creation of boot diskette b. Managing linux network

c. Multiboot d. Linux configuration

5. A Linux system must contain

a. Swap partition b. root password c. linux native partition d. all of these

6. Setup command helps to configure

a. Only X windows b. Mouse c. Sound card d. all of these

MSIT 3A Linux Internals 175

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 175: MSIT 3A

III. Say True or False1. Linear mode option must be used for multi boot option with size of first

partition more than 1023 cylinders. True/False

2. Formatting of all the partitions or mount points is a must for Linux installation True/False

3. /dev mount point contains all user files and information. True/False

4. fdisk command is used to create boot diskette. True/False

4. Windows NT operating system can not be installed as dual boot for linux. True/False

IV. Essay type questions1. Explain how to create an installation or boot diskette.

2. Illustrate the significance of /etc/fstab file with respect to installation.

3. Elucidate the different types of partition sizes required for linux installation.

4. What is partitioning of hard disk drive? Why it is important explain.

5. Describe the possible benefits of partitioning of hard disk drive.

6. Describe the network administration tools and commands with options.

7. Explain the usage of /, swap, /home, /usr mount points with respect to linux installation.

8. What is LILO? How it is useful in Linux.

9. Enumerate the full hardware details of a computer involving all parts.

10. Explain how the updations of packages can be done in Linux.

11. Brief the function of the command linuxconf.

12. What is a tar file? Explain its options in detail.

13. What is a rpm utility? Explain its options in detail.

14. Explain the Partitioning utility fdisk in detail with its different options.

15. Describe the standard linux filesystem types with its significance.

16. Write a detail note on Linux installation.

Chapter 9 - Installation of Linux176

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 176: MSIT 3A

V. Further readings and other activitiesØ Get more information using man or info or any help command for

linuxconf, fs, lilo, setup, Xconfigurator, fdisk, sndconfig, mouseconfig, netconf,neconfig, userconf, ipcalc, fstab, disk, sfdisk, tar, rpm.EX: 1. $ man sfdisk 2. $ apropos nysysv 3. info mtools

Ø For further readings you can refer the following books

1. Title: Linux internalsAuihors: M.V.Panduranga Rao and K.Roopa, JNNCE, Shimoga

http://www.pandurangarao.i8.com/doc/linux/linuxbook.htmlhttp://www.raomvp.bravepages.com/doc/linux/linuxbook.htmlhttp://www.geocities.com/raomvp/doc/linux/linuxbook.htmlA complete reference for you to get more information.

2. Title: The Complete Reference Linux Foutth EditionAuthor: Richard PetersenPublication: Tata McGraw-Hill

3. Title: Red Hat Linux Starter kit in 24 hoursAuthor: Judith Samson etal Publication: Sams Techmedia

4. Title: Unix Shell ProgrammingAuthor: Yashawant Kanitkar Publication: BPB

5. Title: Linux Kernel InternalsAuthor: M. Beck etalPublication: Addison-Wesley, Second Edition

6. Title: Unix Power ToolsAuthor: Jerry Peek etalPublication: BPB

7. Title: Unix System ProgrammingAuthor: Richard Stevens

8. Title: Linux System Administration Handbook - for detail information on problems of linuxinstallation.

MSIT 3A Linux Internals 177

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 177: MSIT 3A

VI. Solutions

I. Choose the correct answer1.d 2.d 3.d 4.c 5.d 6.d

II. Say True or False 1.True 2.True 3.False 4.False 5.False

Chapter 9 - Installation of Linux178

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 178: MSIT 3A

Chapter 10

Glossary

GLOSSARY OF TERMS$HOME

Environment variable that points to your login directory.

$PATH

The shell environment variable that contains a set of directories to be searched for LINUX commands.

/dev/null file

The place to send output that you are not interesting in seeing; also the place to get input from whenyou have none (but the program or command requires something). This is also known as the bit bucket,which is where old bits go to die.

/etc/cshrc file

The file containing shell environment characteristics common to all users that use the C Shell.

/etc/group file

This file contains information about groups, the users they contain, and passwords required for accessby other users. The password may actually be in another file—the shadow group file—to protect it fromattacks.

/etc/inittab file

The file that contains a list of active terminal ports for which LINUX will issue the login prompt. Thisalso contains a list of background processes for LINUX to initialize. Some versions of LINUX use otherfiles like /etc/tty.

MSIT 3A Linux Internals 179

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 179: MSIT 3A

/etc/motd file

Message Of The Day file usually contains information the system administrator feels is important foryou to know. This file is displayed when the user signs on the system.

/etc/passwd file

Contains user information and password. The password may actually be in another file—the shadowpassword file—to protect it from attacks.

/etc/profile

The file containing shell environment characteristics common to all users that use the Bourne andKorn shells.

abbreviation

(vi) User-defined character sequences that are expanded into the defined text string when typedduring insert mode.

absolute pathname

The means used to represent the location of a file in a directory by specifying the exact locationincluding all directories in the chain including the root.

API (Application Program Interface)

The specific method prescribed by a computer operating system, application, or third-party tool bywhich a programmer writing an application program can make requests of the operating system.

arguments

See parameters.

ARPA

See DARPA.

ASCII (American Standard Code for Information Interchange)

Used to represent characters in memory for most computers.

AT&T UNIX

Original version of UNIX developed at AT&T Bell Labs, which was later known as UNIX SystemsLaboratories. Many current versions of UNIX are descendants; even BSD UNIX was derived fromearly AT&T UNIX.

Chapter 10 - Glossary180

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 180: MSIT 3A

attribute

The means of describing objects. The attributes for a ball might be: rubber, red, 3 cm in diameter. Thebehavior of the ball might be how high it bounces when thrown. Attribute is another name for the datacontained within an object (class).

AWK

Programming language developed by A.V. Aho, P.J. Weinberger, and Brian W. Kernighan. The languageis built on C syntax, includes the regular expression search facilities of grep, and adds in the advancedstring and array handling features that are missing from the C language. nawk, gawk, and POSIX awkare versions of this language.

background

Processes usually running at a lower priority and with their input disconnected from the interactivesession. Any input and output are usually directed to a file or other process.

background process

An autonomous process that runs under LINUX without requiring user interaction.

backup

The process of storing the LINUX system, applications, and data files on removable media for futureretrieval.

bash

BASH stands for GNU Bourne Again Shell, and is based on the Bourne shell, sh, the original commandinterpreter.

beep

Usually referred to in LINUX documentation as the bell (see bell).

bell

The character sent by a program to a terminal to indicate some kind of “error” condition; for example,in vi pressing Esc to exit insert mode when you are already in command mode; actually the ̂ G characterwhich rather than displaying on the terminal instead causes it to sound an “alarm,” which on ancientteletype terminals was implemented as a bell. Different terminals produce different sounds for their bellsincluding one old video terminal that sounded like someone shifting gears without benefit of clutch.

binding

(emacs) The assignment of a shift-key sequence to an Emacs editing command.

MSIT 3A Linux Internals 181

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 181: MSIT 3A

block-special

A device file that is used to communicate with a block oriented I/O device. Disk and tape drives areexamples of block devices. The block-special file refers to the entire device. You should not use this fileunless you want to ignore the directory structure of the device (that is, if you are coding a device driver).

boot or boot up

The process of starting the operating system (LINUX).

Bourne Shell

The original standard user interface to UNIX that supported limited programming capability.

BSD UNIX

Version of UNIX developed by Berkeley Software Distribution and written at UC Berkeley

buffer

(vi) The working version of the file you are editing is usually called the buffer; the buffer is actually animage of the file kept in random access memory during editing; changes are made in this image and onlywritten out to disk upon user command (or when the vi autowrite setting is in effect); see also namedbuffer and undo buffer.

buffer list

(emacs) A special window which shows all of the buffers currently open; allows you to manipulatebuffers using buffer list commands.

C

Programming language developed by Brian W. Kernighan and Dennis M. Ritchie. The C language ishighly portable and available on many platforms including mainframes, PCs, and, of course, UNIX systems.

C Shell

A user interface for UNIX written by Bill Joy at Berkeley. It also features C programming-like syntax.

CD-ROM (Compact Disk-Read Only Memory)

Computer-readable data stored on the same physical form as a musical CD. Large capacity, inexpensive,slower than a hard disk, and limited to reading. There are versions that are writable (CD-R, CD Recordable)and other formats that can be written to once or many times.

CGI (Common Gateway Interface)

A means of transmitting data between Web pages and programs or scripts executing on the server.Those programs can then process the data and send the results back to the users browser throughdynamically creating HTML.

Chapter 10 - Glossary182

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 182: MSIT 3A

character-special

A device file that is used to communicate with character-oriented I/O devices such as terminals,printers, or network communications lines. All I/O access is treated as a series of bytes (characters).

characters

1. alphabetic

The letters A through Z and a through z.

2. alphanumeric

The letters A through Z and a through z, and the numbers 0 through 9.

3. control

Any non-printable characters. The characters are used to control devices, separate records, andeject pages on printers.

4. numeric

The numbers 0 through 9.

5. special

Any of the punctuation characters or printable characters that are not alphanumeric. Include thespace, comma, period, and many others.

child-process

See sub-process.

child-shell

See sub-shell.

class

A model of objects that have attributes (data) and behavior (code or functions). It is also viewed as acollection of objects in their abstracted form.

command line

(1) The shell command line from which the current vi or Emacs session was started; (2) the excommand line, where ex commands are entered.

command line editing

LINUX shells support the ability to recall a previously entered command, modify it, and then executethe new version. The command history can remain between sessions (the commands you did yesterdaycan be available for you when you log in today). Some shells support a command line editing mode thatuses a subset of the vi, emacs, or gmacs editor commands for command recall and modification.

MSIT 3A Linux Internals 183

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 183: MSIT 3A

command line history

See command line editing.

command line parameters

Used to specify parameters to pass to the execute program or procedure. Also known as commandline arguments.

command prompt

See shell prompt.

completion

(emacs) The automatic provision of the rest of a command or a file name; when the command or filename cannot be resolved to a single entity, a menu of choices is provided (type a few characters of thename and press TAB; Emacs will either complete the name or give you a menu of choices).

configuration files

Collections of information used to initialize and set up the environment for specific commands andprograms. Shell configuration files set up the user’s environment.

configuration files, shell

For Bourne shell: /etc/profile and $HOME/.profile.

For Korn shell: /etc/profile, $HOME/.profile, and ENV= file.

For C shell: /etc/.login, /etc/cshrc, $HOME/.login, $HOME/.cshrc, and $HOME/.logout. Older versionsmay not support the first two files listed.

For BASH: /etc/profile/, $HOME/.bash_profile, $HOME/.bash_login, $HOME/.profile, $HOME/.bashrc, ~/.bash_logout.

control keys

These are keys that cause some function to be performed instead of displaying a character. Thesefunctions have names, for instance, the end-of-file key tells the LINUX that there is no more input. Thetypical end-of-file key is the <^D> (control-d) key.

CPU (Central Processing Unit)

The primary “brain” of the computer; the calculation engine and logic controller.

current macro

(emacs) The most recently recorded macro; it is executed by the call-last-kbd-macro function.

Chapter 10 - Glossary184

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 184: MSIT 3A

cursor

The specific point on the screen where the next editing action will take place; the cursor is usuallyindicated on the screen by some sort of highlighting, such as a underscore or a solid block, which may ormay not be blinking.

daemon

A system related background process that often runs with the permissions of root and services requestsfrom other processes.

DARPA (U.S. Department of Defense Advanced Research Projects Agency)

Funded development of TCP/IP and ARPAnet (predecessor of the Internet).

database server

See server, database.

default settings

Most tools and systems are governed by a number of settings; those that are in effect when the tool isstarted is known as the default. vi is governed by a number of settings; the default settings are those ineffect when vi is first started and no automatic overrides of settings are in effect through .exrc files orEXINIT environment variables.

device file

File used to implement access to a physical device. This provides a consistent approach to access ofstorage media under LINUX—data files and devices (such as tapes and communication facilities) areimplemented as files. To the programmer, there is no real difference.

directory

A means of organizing and collecting files together. The directory itself is a file that consists of a list offiles contained within it. The root (/) directory is the top level and every other directory is contained in it(directly or indirectly). A directory might contain other directories, which are known as sub-directories.

directory navigation

The process of moving through directories is known as navigation. Your current directory is known asthe current working directory. Your login directory is known as the default or home directory. Using the cdcommand, you can move up and down through the tree structure of directories.

DNS (Domain Name Server)

Used to convert the name of a machine on the Internet (name.domain.com) to the numeric address(123.45.111.123).

MSIT 3A Linux Internals 185

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 185: MSIT 3A

DOS (Disk Operating System)

Operating system that is based on the use of disks for the storage of commands. It is also a genericname for MS-DOS and PC-DOS on the Personal Computer. MS-DOS is the version Microsoft sells andPC-DOS is the version IBM sells. Both are based on Microsoft code.

EBCDIC (Extended Binary Coded Decimal Interchange Code)

The code used to represent characters in memory for mainframe computers.

echo

The display on the screen of characters you type is sometimes called the echo of characters; it iscalled this because usually your terminal is set up not to display the characters directly as typed, but ratherto wait for them to be sent to the computer, which then echoes (sends) them back to your terminal.

ed

A common tool used for line-oriented text editing.

e-mail

Messages sent through an electronic medium instead of through the local postal service. There aremany proprietary e-mail systems that are designed to handle mail within a LAN environment; most ofthese are also able to send over the Internet. Most Internet (open) e-mail systems make use of MIME tohandle attached data (which can be binary).

emacs

A freely available editor now part of the GNU software distribution. Originally written by Richard M.Stallman at MIT in the late 1970’s, it is available for many platforms. It is extremely extensible and has itsown programming language; the name stands for Editing with MACroS.encapsulation. The process ofcombining data (attributes) and functions (behavior in the form of code) into an object. The data andfunctions are closely coupled within an object. Instead of every programmer being able to access the datain a structure his own way, programmers have to use the code connected with that data. This promotescode reuse and standardized methods of working with the data.

environment variables

See variables, environmental.

escape

(1) (vi) The Esc key, used to terminate insert mode, or an incomplete vi command; (2) To prevent acharacter from having its normal interpretation by a program by preceding it with the escape character(usually \, the backslash); for example in a regular expression, to search for a literal character that has aspecial meaning in a regular expression, it must be escaped; as a specific example, to search for a period

Chapter 10 - Glossary186

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 186: MSIT 3A

(.), you must type it escaped as \.

ethernet

A networking method where the systems are connected to a single shared bus and all traffic is availableto every machine. The data packets contain an identifier of the recipient, which is the only machine thatshould process that packet.

expression

A constant, variable, or operands and operators combined. Used to set a value, perform a calculation,or set the pattern for a comparison (regular expressions).

fifo

First In, First Out. See named pipe.

file

Collection of bytes stored on a device (typically a disk or tape). Can be source code, executablebinaries or scripts, or data.

1. indexed

A file based on a file structure where data can be retrieved based on specific keys (name, employeenumber, and so on) or sequentially. The keys are stored in an index. This is not directly supported by theLINUX operating system; usually implemented by the programmer or by using tools from an ISV. Atypical form is known as ISAM.

2. line sequential

See file, text.

3. sequential

a. A file that can only be accessed sequentially (not randomly).

b. A file without record separators. Typically fixed length but LINUX does not know what that lengthis and does not care.

4. text

A file with record separators. May be fixed or variable length; LINUX tools can handle these filesbecause it can tell when the record ends (by the separator).

file compression

The process of applying mathematical formula to data typically resulting in a form of the data that

MSIT 3A Linux Internals 187

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 187: MSIT 3A

occupies less space. A compressed file can be uncompressed (lossless) resulting in the original file. Whenthe compression/uncompress process results in exactly the same file as was originally compressed, it isknown as lossless. If information about the original file is lost, the compression method is know as lossy.Data and programs need lossless compression; images and sounds can stand lossy compression.

filename

The name used to identify a collection of data (a file). Without a pathname, it is assumed to be in thecurrent directory.

filename generation

The process of the shell interpreting meta-characters (wild cards) to produce a list of matching files.This is referred to as filename expansion or globbing.

filename, fully qualified

The name used to identify a collection of data (a file) and its location. It includes both the path andname of the file; typically, the pathname is fully specified (absolute). See also pathname and pathname,absolute.

filesystem

A collection of disk storage that is connected (mounted) to the directory structure at some point(sometimes at the root). Filesystems are stored in a disk partition and are also referred to as disk partitions.

firewall

A system used to provide a controlled entry point to the internal network from the outside (usually theInternet). This is used to prevent outside or unauthorized systems from accessing systems on your internalnetwork. The capability depends on the individual software package, but the features typically include:filter packets, filter datagrams, provide system (name or IP address) aliasing, and rejecting packets fromcertain IP addresses. It can also prevent internal systems from accessing the Internet on the outside. Intheory, it provides protection from malicious programs or people on the outside. The name comes from thephysical barrier between connected buildings or within a single building that is supposed to prevent firefrom spreading from one to another.

flags

See options.

foreground

Programs running while connected to the interactive session.

fseek

Chapter 10 - Glossary188

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 188: MSIT 3A

Internal function used by LINUX to locate data inside a file or filesystem. ANSI standard fseekaccepts a parameter that can hold a value of +2 to -2 billion. This function, used by the operating system,system tools, and application programs, is the cause of the 2 GB file and filesystem size limitation on mostsystems. With 64 bit operating systems, this limit is going away.

FTP (File Transfer Protocol, or File Transfer Program)

A system-independent means of transferring files between systems connected via TCP/IP. Ensuresthat the file is transferred correctly, even if there are errors during transmission. Can usually handlecharacter set conversions (ASCII/EBCDIC) and record terminator resolution (<lf> for LINUX, <cr>and <lf> for MS/PC-DOS).

gateway

A combination of hardware, software, and network connections that provides a link between onearchitecture and another. Typically, a gateway is used to connect a LAN or LINUX server with a mainframe(that uses SNA for networking resulting in the name: SNA gateway). A gateway can also be the connectionbetween the internal and external network (often referred to as a firewall). See also firewall.

globbing

See filename generation.

GNU

GNU stands for GNU’s Not Unix, and is the name of free useful software packages commonly foundin UNIX environments that are being distributed by the GNU project at MIT, largely through the effortsof Richard Stallman.

grep

A common tool used to search a file for a pattern. egrep and fgrep are newer versions. Egrep allowsthe use of extended (hence the “e” prefix) regular expressions, fgrep uses limited expressions for a faster(hence the “f” prefix) searches.

here document

The << redirection operator, known as here document, allows keyboard input (stdin) for the programto be included in the script.

HTML (HyperText Markup Language)

Describes World Wide Web pages. It is the document language that is used to define the pagesavailable on the Internet through the use of tags. A browser interprets the HTML to display the desiredinformation.

MSIT 3A Linux Internals 189

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 189: MSIT 3A

i-node

Used to describes a file and its storage. The directory contains a cross reference between the i-nodeand pathname/filename combination. Also known as inode.

I-Phone (Internet Phone)

A method of transmitting speech long distances over the Internet in near real-time allowing theparticipants to avoid paying long distance telephone charges. They still pay for the call to their ISP and theISP’s service charges.

ICMP (Internet Control Message Protocol)

Part of TCP/IP that provides network layer management and control.

inheritance

A method of object-oriented software reuse in which new classes are developed based on existingones by using the existing attributes and behavior and adding on to them. For example, if the base objectis automobile with attributes of an engine, four wheels, and tires, and behavior of acceleration, turning, anddeceleration, then a sports car would modify the attributes so the engine would be larger or have morehorsepower than the default, the four wheels would include alloy wheels and high speed rated tires, andthe behavior would also be modified for faster acceleration, tighter turning radius, and faster deceleration.

inode

See i-node.

Internet

A collection of different networks that provide the ability to move data between them. It is built on theTCP/IP communications protocol. Originally developed by DARPA, it was taken over by NSF, and hasnow been released from governmental control.

Internet Service Provider

The people who connect you to the Internet.

IRC (Internet Relay Chat)

A server-based application that allows groups of people to communicate simultaneously through text-based conversations. IRC is similar to Citizen Band radio or the “chat rooms” on some bulletin boards.Some chats can be private (between invited people only) or public (where anyone can join in). IRC nowalso supports sound files as well as text

it can also be useful for file exchange.

Chapter 10 - Glossary190

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 190: MSIT 3A

ISAM (Indexed Sequential Access Method)

On LINUX and other systems, ISAM refers to a method for accessing data in a keyed or sequentialway. The LINUX operating system does not directly support ISAM files; they are typically add onproducts.

ISP

See Internet Service Provider.

ISV (Independent Software Vendor)

Generic name for software vendors other than your hardware vendor.

kernel

The core of the operating system that handles tasks such as memory allocation, device input andoutput, process allocation, security, and user access. LINUX tends to have a small kernel when comparedto other operating systems.

keyboard macros

A feature which allows a special key sequence to stand for another, usually more complex sequence;in vi, keyboard macros are implemented via the :map command.

kill ring

(emacs) A set of buffers where killed text is kept; the buffers are arranged in a circular pattern. Whencommands that automatically move from one buffer to the next get to the end of the set, the next movementwill be to the first buffer in the ring.

Korn Shell

A user interface for LINUX with extensive scripting (programming) support. Written by David G.Korn. The shell features command line editing and will also accept scripts written for the Bourne Shell.

LAN (Local Area Network)

A collection of networking hardware, software, desktop computers, servers, and hosts all connectedtogether within a defined local area. A LAN could be an entire college campus.

limits

See quota.

line address

(vi and ex) The way a selected set of lines is indicated in ex mode is through a line address. A lineaddress can be an absolute line number, relative line number, or special symbols which refer to thebeginning or of the file.

MSIT 3A Linux Internals 191

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 191: MSIT 3A

link

1. hard

Directory entry that provides an alias to another file that is in the same filesystem. Multiple entriesappear in the directory (or other directories) for one physical file without replication of the contents.

2. soft

See symbolic link.

3. symbolic

Directory entry that provides an alias to another file that can be in another filesystem. Multiple entriesappear in the directory for one physical file without replication of the contents. Implemented through linkfiles; see also link file.

4. file

File used to implement a symbolic link producing an alias on one filesystem for a file on another. Thefile only contains the fully qualified filename of the original (linked-to) file.

lisp

A programming language used in artificial intelligence. The name stands for LISt Processing. It is theprogramming language that Emacs is written in and also refers to three major modes within it.

literal text string

An exact character text string, with no wildcards.

login

The process that a user gains access to a LINUX system. This can also refer to the user id that istyped at the login prompt.

macro

A recorded series of keystrokes which can be played back to accomplish the same task repetitively.

major mode

(emacs) A named set of behavioral characteristics; a buffer can be in only one major mode at a time.For examples, text mode for writing a letter; c mode for writing c source code.

man page

On-line reference tool under LINUX that contains the documentation for the system—the actualpages from the printed manuals. It is stored in a searchable form for improved capability to locateinformation.

Chapter 10 - Glossary192

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 192: MSIT 3A

manual page

See man page.

mappings

(vi) User-defined character sequences (which may include control keys) that are interpreted as acommand sequence (which may also include control keys).

memory

1. real

The amount of storage that is being used within the system (silicon; it used to be magnetic cores).

2. virtual

Memory that exists but you cannot see. Secondary storage (disk) is used to allow the operating systemto allow programs to use more memory than is physically available. Part of a disk is used as a paging fileand portions of programs and their data are moved between it and real memory. To the program, it is inreal memory. The hardware and operating system performs translation between the memory address theprogram thinks it is using the where it is actually stored.

meta-character

A printing character that has special meaning to the shell or another command. It is converted intosomething else by the shell or command - the asterisk <*> is converted by the shell to a list of all files inthe current directory.

MIME (Multipurpose Internet Mail Extensions)

A set of protocols or methods of attaching binary data (executable programs, images, sound files, andso on) or additional text to e-mail messages.

mini-buffer

(emacs) The last line on the screen, where commands are entered.

minor mode

(emacs) A particular characteristic which can be independently toggled on or off. For example, auto-fill mode for easing the creation of document text.

mode

Many programs offer only subsets of their functions at any given time, because only certain functionsare relevant within an immediate context; further, the same keystroke may invoke different commands inthese different contexts; such a context is referred to as a mode. Major modes in vi are insert mode (foradding new text into the buffer), and command mode (for most other editing actions).

MSIT 3A Linux Internals 193

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 193: MSIT 3A

MPTN (MultiProtocol Transport Network)

IBM networking protocol to connect mainframe to TCP/IP network.

named buffer

(vi)A memory location where text objects can be stored during a single vi session; named bufferspersist when you switch from one file to another during a session and are the primary way of moving andcopying text between files.

named pipe

An expanded function of a regular pipe (redirecting the output of one program to become the input ofanother). Instead of connecting stdout to stdin, the output of one program is sent to the named pipe andanother program reads data from the same file. This is implemented through a special file known as a pipefile or fifo. The operating system ensures the proper sequencing of the data. Little or no data is actuallystored in the pipe file; it just acts as a connection between the two.

Netnews

This is a loosely controlled collection of discussion groups. A message (similar to an e-mail) is postedin a specific area and then people can comment on it, publicly replying to the same place (“posting aresponse”) for others to see. A collection of messages along the same theme is referred to as a thread.Some of the groups are moderated, which means that nothing is posted without the approval of the“owner.” Most are not and the title of the group is no guarantee that the discussion will be related. The“official” term for this is Usenet News.

NFS (Network File System)

Means of connecting disks that are mounted to a remote system to the local system as if they werephysically connected.

NIS (Network Information Service)

A service that provides information necessary to all machines on a network, such as NFS support forhosts and clients, password verification, and so on.

NNTP (Net News Transport Protocol)

Used to transmit Netnews or usenet messages over top of TCP/IP. See Netnews for more informationon the messages transmitted.

null statement

A program step that performs no operation but to hold space and fulfill syntactical requirements of theprogramming language. Also known as a NO-OP for no-operation performed.

Chapter 10 - Glossary194

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 194: MSIT 3A

numeric setting

A setting which takes a numeric value, rather than an enabled or disabled state. Applies to many toolsincluding vi and the different shells.

object

An object in the truest sense of the word is something that has physical properties, such as automobiles,rubber balls, and clouds. These things have attributes and behavior. They can be abstracted into data(attribute) and code (behavior). Instead of just writing functions to work on data, they are encapsulatedinto a package that is known as an object.

open mode

The visual mode of the ex editor.

operator

Meta-character that performs a function on values or variables. The plus sign <+> is an operator thatadds two integers.

options

Program- or command-specific indicators that control behavior of that program. Sometimes calledflags. The -a option to the ls command shows the files that begin with a . (such as .profile, .kshrc, and soon.) Without it, these files would not be shown, no matter what wildcards were used. These are used onthe command line. See also parameters.

package

(emacs) A feature set which can be added to the editor. Major modes and many functions areimplemented via packages. Numerous packages are built in to standard Emacs; many others are freely orotherwise available.

parameters

Data passed to a command or program through the command line. These can be options (see options)that control the command or arguments that the command works on. Some have special meaning basedon their position on the command line.

parent process identifier

Shown in the heading of the ps command as PPID. The process identifier of the parent-process. Seealso parent-process.

parent-process

Process that controls another often referred to as the child- or sub-process. See process.

MSIT 3A Linux Internals 195

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 195: MSIT 3A

parent-shell

Shell (typically the login shell) that controls another, often referred to as the child- or sub-shell. Seeshell.

password

The secure code that is used in combination with a user id to gain access to a LINUX system.

pathname

The means used to represent the location of a file in the directory structure. If you do not specify apathname, it defaults to the current directory. Also see absolute pathname and relative pathname.

PDP (Personal Data Processor)

Computers manufactured by Digital Equipment Corporation. LINUX was originally written for a PDP-7 and gained popularity on the PDP-11. The entire series were inexpensive mini-computers popular witheducational institutions and small businesses.

Perl (Practical Extraction and Report Language)

Programming language developed by Larry Wall. (Perl stands for “Practical Extraction and ReportLanguage” or “Pathologically Eclectic Rubbish Language”, both are equally valid). The language providesall of the capabilities of awk and sed, plus many of the features of the shells and C.

permissions

When applied to files, they are the attributes that control access to a file. There are three levels ofaccess: owner (the file creator), group (people belonging to a related group as determined by the systemadministrator), and other (everyone else). The permissions may be r for read, w for write, and x forexecute. The execute permissions flag is also used to control who may search a directory.

pipe

A method of sending the output of one program (redirecting) to become the input of another. The pipecharacter <|> tells the shell to perform the redirection.

pipe file

See named pipe.

polymorphism

Allows code to be written in a general fashion to handle existing and future related classes. Properlydeveloped, the same behavior can act differently depending on the derived object it acts on. With anautomobile, the acceleration behavior might be different for a station wagon and a dragster which are

Chapter 10 - Glossary196

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 196: MSIT 3A

subclasses of the superclass automobile. The function would still be accelerate(), but the version wouldvary (this may sound confusing, but the compiler keeps track and figures it all out).

POSIX

POSIX stands for “Portable Operating System Interface, UNIX”. It is the name for a family of opensystem standards based on UNIX. The name has been credited to Richard Stallman. The POSIX Shelland Utilities standard developed by IEEE Working Group 1003.2 (POSIX.2) concentrates on the commandinterpreter interface and utility programs.

PPP (Point-to-Point Protocol)

Internet protocol over serial link (modem).

process

A discrete running program under LINUX. The user’s interactive session is a process. A process caninvoke (run) and control another program that is then referred to as a sub-process. Ultimately, everythinga user does is a subprocess of the operating system.

process identifier

Shown in the heading of the ps command as PID. The unique number assigned to every processrunning in the system.

quota

General description of a system-imposed limitation on a user or process. It can apply to disk space,memory usage, CPU usage, maximum number of open files, and many other resources.

quoting

The use of single and double quotes to negate the normal command interpretation and concatenate allwords and whitespace within the quotes as a single piece of text.

range

(vi, ed, and ex) a line address which indicates one or more lines from a starting line to an ending line;indicated as start,end where both start and end are individual line addresses.

recursive edit

(emacs) A feature that allows a query-replace operation to be temporarily suspended while otherediting is done.

redirection

The process of directing a data flow from the default. Input can be redirected to get data from a file or

MSIT 3A Linux Internals 197

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 197: MSIT 3A

the output of another program. Normal output can be sent to another program or a file. Errors can be sentto another program or a file.

regular expression

A way of specifying and matching strings for shells (filename wildcarding), grep (file searches), sed,and awk.

relative pathname

The means used to represent the location of a file in a directory other than the current by navigating upand down through other directories using the current directory as a base.

reserved word

A set of characters recognized by LINUX and related to a specific program, function, or command.

RFC (Request For Comment)

Document used for creation of Internet and TCP/IP related standards.

rlogin (Remote Login)

Gives the same functionality of telnet, with the added functionality of not requiring a password fromtrusted clients, which can also create security concerns. See telnet.

root

1) The user who owns the operating system and controls the computer. 2) The processes of theoperating system run as though a user, root, signed on and started them. The root user is all powerful andcan do anything he or she wants. For this reason, the root user is often referred to as a super-user. It isalso the very top of the directory tree structure.

routing

The process of moving network traffic between two different physical networks; also decides whichpath to take when there are multiple connections between the two machines. It may also send trafficaround transmission interruptions.

RPC (Remote Procedural Call)

Provides the capability to call functions or subroutines that run on a remote system from the local one.

scripts

A program written for a LINUX utility including shells, AWK, perl, sed, and others. Also see shellscripts.

Chapter 10 - Glossary198

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 198: MSIT 3A

sed

A common tool used for stream text editing, having ed-like syntax.

server, database

A system designated to run database software (typically a relational database like Oracle, SQL Server,Sybase, or others). Other systems connect to this one to get the data (client applications).

settings

vi is governed by a number of internal variable called settings; these control how certain actions takeplace.

Shell

The part of LINUX that handles user input and invokes other programs to run commands. Includes aprogramming language. See also Bourne Shell, C Shell, Korn Shell, tcsh, and BASH.

shell environment

The shell program (Bourne, Korn, C, tcsh, or BASH), invocation options, and preset variables thatdefine the characteristics, features and functionality of the LINUX command line and program executioninterface.

shell buffer

(emacs) A buffer in which an interactive LINUX shell session has been started.

shell scripts

A program written using a shell programming language like those supported by Bourne, Korn, or Cshells.

shift-key sequence

(emacs) To perform a shift-key sequence, hold down the designated shift key (for example, Shift,Ctrl, Alt, or Meta), then press the second designated key, then release both keys. When typing severalconsecutive shift-key sequences that use the same shift key, you can keep holding down the shift key forthe duration.

signal

A special flag or interrupts that is used to communicate special events to programs by the operatingsystem and other programs.

SLIP (Serial Line Internet Protocol)

MSIT 3A Linux Internals 199

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 199: MSIT 3A

Internet over a serial link (modem). The protocol frames and controls the transmission of TCP/IPpackets of the line.

SNA(System Network Architecture)

IBM networking architecture.

special keys

See control keys.

stderr

The normal error output for a program that is sent to the screen by default. Can be redirected to a file.

stdin

The normal input for a program, taken from the keyboard by default. Can be redirected to get inputfrom a file or the output of another program.

stdout

The normal output for a program that is sent to the screen by default. Can be redirected to a file or tothe input of another program.

sticky bit

One of the status flags on a file that tells LINUX to load a copy of the file into the page file the firsttime it is executed. This is done for programs that are commonly used so the bytes are available quickly.When the sticky bit is used on frequently used directories, they are cached in memory.

stream

A sequential collection of data. All files are streams to the LINUX operating system. To it, there is nostructure to a file—that is something imposed by application programs or special tools (ISAM packagesor relational databases).

sub-directory

See directory.

sub-process

Process running under the control of another, often referred to as the parent-process. See process.

sub-shell

Shell running under the control of another, often referred to as the parent-shell (typically the loginshell). See shell.

Chapter 10 - Glossary200

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 200: MSIT 3A

subnet

A portion of a network that shares a common IP address component. Used for security and performancereasons.

super-user

See root.

system administrator

The person who takes care of the operating system and user administrative issues on LINUX systems.Also called a system manager although that term is much more common in DEC VAX installations.

system manager

See system administrator.

system programmer

See system administrator.

TCP/IP (Transport Control Protocol/Internet Protocol)

The pair of protocols and also generic name for suite of tools and protocols. that forms the basis for theInternet. Originally developed to connect systems to the ARPANET.

tcsh

A C shell-like user interface featuring command-line editing.

Telnet

Protocol for interactive (character user interface) terminal access to remote systems. The terminalemulator that uses the telnet protocol is often known as telnet or tnvt100.

Terminal

A hardware device, normally containing a cathode ray tube (screen) and keyboard for human interactionwith a computer system.

text object

(vi) A text object is the portion of text in the buffer that would be traversed by a specific movementcommand; for example w refers to the next small word.

text processing languages

A way of developing documents in text editors with embedded commands that handle formatting. The

MSIT 3A Linux Internals 201

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 201: MSIT 3A

file is fed through a processor that executes the embedded commands producing a formatted document.These include roff, nroff, troff, RUNOFF, TeX, LaTeX, and even the mainframe SCRIPT.

TFTP (Trivial File Transfer Protocol or Trivial File Transfer Program)

A system-independent means of transferring files between systems connected via TCP/IP. It is differentfrom FTP in that it does not ensure that the file is transferred correctly, does not authenticate users, andis missing a lot of functionality (like the ls command).

toggle

A mode that is alternately turned on and off by successive entry of its command.

toggle setting

(vi) A setting which is either enabled or disabled; for example, for the fictitious setting named option,you would enable the setting by entering the command :set option; you would disable the setting byentering the command :set nooption.

top

A common tool used to display information about the top processes on the system.

typewriter key

The subset of a terminal keyboard that is on a standard typewriter; generally the alphanumeric keys,but not the function, cursor control, or numeric pad keys.

UDP (User Datagram Protocol)

Part of TCP/IP used for control messages and data transmission where the delivery acknowledgmentis not needed. The application program must ensure data transmission in this case.

undo buffer

(vi) A location in memory where the most recent deleted text object is saved, either for later undoingof the deletion, or for copying of the object to another location.

URL (Uniform Resource Locator)

The method of specifying the protocol, format, login (usually omitted), and location of materials on theInternet.

Usenet

See Netnews.

UUCP (UNIX-to-UNIX-Copy-Program)

Chapter 10 - Glossary202

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 202: MSIT 3A

Used to build an early, informal network for the transmission of files, e-mail, and Netnews.

variables, attributes

The modifiers that set the variable type. A variable can be string or integer, left or right justified, read-only or changeable, and other attributes.

variables, environmental

A place to store data and values (strings and integers) in the area controlled by the shell so they areavailable to the current and sub-processes. They can just be local to the current shell or available to a sub-shell (exported).

variables, substitution

The process of interpreting an environmental variable to get its value.

viewport

The portion of the buffer that appears in a window on your screen; one way to think of moving throughthe buffer is to think of the viewport as sliding back and forth through the buffer.

Web

See World Wide Web.

whitespace

Blanks, space and tabs that are normally interpreted to delineate commands and filenames unlessquoted.

wildcard

Means of specifying filename(s) where the operating system determines some of the characters.Multiple files may match and will be available to the tool.

window

The portion of your screen which is displaying a viewport into a buffer.

World Wide Web

A collection of servers and services on the Internet that run software that communicate using acommon protocol (HTTP). Instead of having to remember the location of these resources, links areprovided from one Web page to another through the use of URLs (Uniform Resource Locators).

WWW

See World Wide Web.

MSIT 3A Linux Internals 203

PDF created with pdfFactory Pro trial version www.pdffactory.com

Page 203: MSIT 3A

X Window System

A windowing and graphics system developed by MIT, to be used in client/server environments.

X

See X Window System.

X11

See X Window System.

X-windows

The wrong term for the X Window System. See X Window System.

Chapter 10 - Glossary204

PDF created with pdfFactory Pro trial version www.pdffactory.com