• No results found

Network Operating Systems Lab Manual

N/A
N/A
Protected

Academic year: 2021

Share "Network Operating Systems Lab Manual"

Copied!
188
0
0

Loading.... (view fulltext now)

Full text

(1)

Network Operating Systems

Lab Manual

(2)

The Practice of Knowledge

Department of Computer Science

COMSATS Institute of Information Technology

Abbottabad

(3)

Network Operating Systems

Lab Manual

Javid Ali

(4)

TABLE OF CONTENTS

Lab No. 01: Linux Basic Installation ... 6

Lab No. 02: Linux shell and Basic shell commands ... 19

Lab No. 03: Command Line File Manipulation ... 23

Lab No. 04: Command Line File processing ... 28

Lab No. 05: Command line Text Editors (Vim) ... 34

Lab No. 06: Managing the file system ... 39

Lab No. 07: Command line Process Management ... 44

Lab No. 08: Basic Bash Scripting, writing and executing bash scripts ... 48

Lab No. 09: Advance Bash Scripting 1 ... 51

Lab No. 10: Advance Bash Scripting 2 ... 54

Lab No. 11: Introduction to gcc ... 57

Lab No. 12: Linux Networking 1 ... 62

Lab No. 13: Linux Networking 2 ... 65

Lab No. 14: Network troubleshooting ... 69

Lab No. 15: Installing Linux Software ... 83

Lab No. 16: Linux Boot Process ... 89

Lab No. 17: Configuring Linux DHCP Server ... 93

Lab No. 18: Managing Linux Users and sudo ... 97

Lab No. 19: Configuring Samba ... 101

Lab No. 20: Sharing Resources using samba ... 107

Lab No. 21 Linux firewalls using iptables ... 111

Lab No. 22: Configuring Linux FTP Server ... 120

Lab No. 23: Telnet and TFTP and XINETD... 126

(5)

Lab No. 25: Monitoring Server Performance ... 134

Lab No. 26: Network Based Linux Installation ... 148

Lab No. 27: Remote Disk Access with NFS ... 159

Lab No. 28: Controlling Web Usage with Squid ... 168

Lab No. 29: DNS Configuration 1... 173

Lab No. 30: DNS Configuration 2... 177

Lab No. 31: DNS Configuration 3... 182

(6)

Lab No. 01: Linux Basic Installation

Objective:

This lab provides a basic step-by-step installation of Linux Operation system. A simple approach has been adopted out of many ways available for different configuration.

Scope:

On completing this exercise, the students will be able to: • Install linux operating system

• Cearte and manage linux disk partitions

• Configure differents system resources during installation • Select packages during installation

Useful Concepts:

Partition

• A space in hard disk set aside as a separate disk and has separate filesystem Mount point

• A logical location in a file system that provide a link to another file system Package

• An application that can be installed on a UNIX/ Linux system. Boot loader

• A small program that runs a the system boot and starts an operating system

Exercise-1:- This exercise demonstrates step-by-step installation of Linux Operation sys-tem. The procedure is shown in Figure 1 – Figure 19 as follows:

• in the boot screen, press Enter

• in the installation welcome screen, click Next • in the language selection screen, click Next • in the keyboard configuration screen, click Next

• in the installation type screen, choose Server and click Next • in the disk partitioning screen, you can select the following option

 remove all linux partition  remove all partion on this disk  keep all partition and use free space

If you choose manual partition, select free space and create the following partition:

Mount Point: Size (MB) Filesystem Type

/boot 200 ext3

--- (size for RAM)*2 swap

/ all available free space ext3 Clicking Next:

(7)

• in the partition warning screen, click Yes • in the partition removal screen, click Next

• in the partitioning removal warning screen, click Yes • in the disk setup screen, click Next

• in the boot loader screen, click Next

• in the network configuration screen, click Next • in the firewall configuration screen, click Next • in the time zone selection screen, choose Asia/Riyadh

• in the root password screen, enter the root password (min. 6 characters) and confirm it, click Next

• In the package group selection screen, you can select different packages to install. Pack-ages are grouped in different categories. Choose pachPack-ages of your choice to install. Serv-er group has sServ-ervServ-er packages like apache, hdcp, squid etc. If you did not select the sServ-ervServ-er installation option in step five, here is the chance that you can select servers of your choice. After selecting packages click next to go to the next screen

• in the about to install screen, click Next

• in the installation status screen, wait while files are installed

• in the installation complete screen, take out the DVD and click Reboot

(8)

Figure 2. Fedora Core installation welcome screen.

(9)

Figure 4. Keyboard configuration screen.

(10)

Figure6. Disk partitioning screen.

(11)

Figure 8. Partition removal screen.

(12)

Figure 10. Disk setup screen.

(13)

Figure 12. Network configuration screen.

(14)
(15)

Figure 15. Root password screen.

(16)

Figure 17. About to install screen.

(17)

Figure 19. Installation complete screen.

Exercises for lab:

Exercise 1:- Actual configuration of the system is left to your discretion except for those particular sec-tions of the installation for which specific direcsec-tions are given. Record every configuration at each step in your notebook clear enough to allow someone else to exactly follow your instal-lation steps.

Home Work:

1) List any problems you had during the installation process, and their solutions. Also, answer the following questions:

• Why did you put /boot in the first location of the hard drive and forced it to be a primary partition?

• What is the advantage of using different partitions for different sections of the filesys-tem?

• Specifically describe the critical difference between the partitions /dev/hda1 and /dev/hda5.

• Why don’t you want to use root as the regular login on your machine?

(18)

To understand the Linux Commands

(19)

Lab No. 02: Linux shell and Basic shell commands

Objective:

To introduce the student to Linux most popular command line shell, the BASH. This lab will cover basic commands used in Unix/Linux.

Scope:

On the completion of this lab, you will be able to: • Describe the bash and its features. • Understand the bash environment.

• Use some frequently-used command in UNIX/ Linux environment.

Useful Concepts:

Shell

• A piece of software that provides an interface for users.

• Typically, an operating system shell which provides access to the services of a kernel. • Generally fall into one of two categories:

i. command-line ii. graphical

Bash (Bourne-again shell) is the default shell on most systems built on top of the Linux kernel as well as on Mac OS X and it can be run on most Unix-like operating systems. Terminal

An instant of a shell that provide an editor for the user to enter commands and run processes Shell Prompt

• Location in the terminal where you can enter commands. • Represented by $ or >

Root directory

/ is the primary directory where all other directories reside. Mount point

The location in the operating system's directory structure where a mounted file system appears Package

Computer software packaged in an archive format to be installed by a package management system or a self-sufficient installer

Boot loader

The small program that starts loading OS into RAM, also known as a bootstrap loader, or bootstrap or

(20)

Exercise-1:- This exercise illustrates how to view content of a directory and move around the file system.

To get a listing of the directory contents, type:

ls

For a long view of the listing with time stamps, file permissions and file ownerships type:

ls -l

To move to directory-name directory type:

cd directory-name

To go to the /etc directory you simply type

cd /etc

To go one step back type:

cd ..

To go to user's home directory, type:

cd ~

To display the path to the directory you r currently working in, type:

pwd

At any point using the TAB key after typing a few characters in at the bash prompt will make bash fill in the rest of the file or directory name that matches what you have typed. If there is more than one match, tap the tab key twice and it will list all the matches.

Exercise-2:- This exercise illustrates how to clear screen contents and display history of command already used in the shell.

If you what to see the list of all commands you have used on the shell, type:

history

To clear the terminal screen, type:

clear

Exercise-3:- This exercise illustrates how to Display or change system date and display cal-endar of different months and years.

To display calendar of the current month type:

cal

To display calendar of the prev/current/next month type

cal -3

To display weeks that starts on Monday, type:

cal -m

To display calendar of March 1988, type: cal 03 1988

To display current system date, type:

date

To change date to Thu Mar 3 23:05:25 2009, type:

(21)

Exercise-4:- This exercise illustrates who to Get help about command and search or

com-mand instances:

To go to manual page of a command, say ls, type:

man ls

To get information about command usage, say ls, type:

info ls

To Report all known instances of a command e.g. ls, type:

whereis ls

To locate a program file in the user's path, type:

which command_name

Exercise-5:- This exercise illustrates the use of miscellaneous commands: To print system name, type:

hostname

To set host name to mylinuxbox@linuxserver, type:

hostname mylinuxbox@linuxserver

To display the linux system information, type:

uname -r

To print all usernames currently logged in, issue the following command.

who

To print the current user id and name, type

whoami Exercises for lab:

Exercise 1:- Open a shell and practice all the commands given above. Use man command to explore the manual page of each command and then try these commands with different options. Note the effect of the options on the output.

Home Work:

1) Write a note on Linux shell?

(22)

To understand the File Manipulation using shell.

(23)

Lab No. 03: Command Line File Manipulation

Objective:

To familiarize the students with basic file and directory management using shell.

Scope:

Student will be able to perform the following tasks at the end of this lab: • The Working Directory

• Listing Directory Contents • Viewing Files

• Copying Files

• Moving and Renaming Files

• Searching for Files by File Name & by Content • Creating & Creating Subdirectories

• Creating Symbolic Links

Useful Concepts:

Working Directory

• A special directory remembered by the shell, and is interpreted to be the directory you are currently “in”.

• Important for situation where relative paths are in use. Symbolic link

• A symbolic (or soft) link is an indirect reference to a file, similar to an “alias” in Mac OS or a “shortcut” in Windows.

Meta characters

• Characters having special meaning to the terminal

• Wildcards are Meta characters that can represent different characters in a string. Following are some Special Characters with a brief description:

Character Function Examples

\ Escape character. If you want to reference a special cha-racter, you must “escape” it

with a backslash first.

touch /tmp/filename\*

/ Directory separator, used to separate a string of directory names.

/usr/src/linux

. Current directory. Can also “hide” files when it is the first character in a filename.

.htaccess

.. Parent directory cd ..

(24)

Exercise -1:- This exercise illustrates how to View contents of a file.

To view file contents on shell console, type:

cat filename

To merge contents of two or more files and display it on screen, type

cat file1 file2 file3 ...

To display display a screenful text of file on the terminal, type:

more filename

To display file contents screenful at a time with page-up and page-down options, type:

less filename

To view first k lines of the file, type:

head -n k filename

e.g, to display first 5 lines of the file myfile on the terminal, type;

head -n 5 myfile

To display last 5 lines of the file myfile on the terminal, type;

tail -n 5 myfile

E

Exxeerrcciisse -2:- This exercise illustrates the procedure of File Copy, move, rename and delete e

command.

To copy a file to the same directory with different name, type:

cp source_fiel_name destination_file_name

To copy a file to a different directory, e.g. from /home/cs to /root type:

cp /home/cs/myfile /root/myfile

To move a file to different destination, type:

mv cource destination

To rename a file, type:

mv oldname newname

To delete the file from directory, type:

rm filename

To delete the file from different directory, the filename must precede full path name, like:

rm /home/cs/myfile

To delete an empty directory, type:

* Represents 0 or more characters in a filename, or by it-self, all files in a directory.

More details in next section

? Represents a single character in a filename. hello?.txt can represent hello1.txt, helloz.txt, but not hello22.txt [ ] Can be used to represent a range of values, e.g. [0-9],

[A-Z], etc

hello[0-2].txt represents the names hello0.txt,

hello1.txt, and hello2.txt ; Command separator. Allows you to execute multiple

commands on a single line.

(25)

rmdir directory_name

To delete a non-empty directory, type:

rm –r directory_name

To delete a file forcefully, type:

rm –f file_name

E

Exxeerrcciisse -3:- This exercise illustrates how to search for files and file types. e

To search a file in the entire disc, locate command is used. Type:

locate filename

To search a file in a particular directory and subdirectories, use find command. Type:

find –name filename directory_name

To access a specific file, say myfile.txt, in the directory and subdirectories, use find command, type:

find . -name myfile.txt -print

To search for all files that begin with the characters com, starting in the directory /home, type:

find /home -name com* -print

To search for a file based on the file’s content instead of its name. use grep command. to search all files in the current directory for the string students type:

grep students ./*

To search all files in the current directory for strings starting with stu and ending with nts, type:

grep stu*nts ./*

To find whether a file is binary file, an executable file or a regular text file etc, type:

file filename

E

Exxeerrcciisse -4:- This exercise illustrates how to creat files or directories and changing time-e

stamps.

To create an empty file, use touch command, type: touch myfile.txt

To create three files, type: touch file1 file2 file3

To change the time of last modification of the file, myfile to 12/04/2009, type: touch -fafsdfsdaf

To create a directory, type; mkdir directory

To create a directory along with the missing directory in the path, type: mkdir –p /home/cs/assingments/assignmet1

To create a symbolic link to a file in cs folder of your home directory from your desktop, type: ln -s ~/cs/friends ~/Desktop/friends

Exercises for lab:

Exercise 1:- write shell commands to carry the following tasks: • Ad a directory named testdir to the following path.

(26)

• Create a file named testfile in testdir directory

• Change the creation date and modification date of the directory to 16/03/1983 • Create a symbolic link from your desktop to testfile

Home Work:

Carry out the following exercises and submit your documented work.

1) Create a directory in the /home/zahid/assignment/assignment1 while your current working direc-tory is /home, using a single shell command.

2) Create a directory with the following names • assign.doc

• assigns.doc • assign.txt • quiz.txt • quiz.cpp

3) Write a command to rename assign.doc file to assignment.doc 4) Delete all files with extension .txt using shell command. 5) Display all files names starting with ‘as’.

(27)

To understand File processing using terminal or command

line shell

(28)

Lab No. 04: Command Line File processing

Objective:

To familiarize students with the directory level and file level security, compressing and archiving tech-niques.

Scope:

On the completion of this lab, students will be able to: • Understand file types used in LINUX system. • View and modify file access permission. • Change the ownership of files and directories • Create backup for critical files using archives

Useful Concepts:

Access Permissions

• The ability of a user to access a file or directory.

• Three general types of permissions are read permission, write permission and execute permission. File owner

• The user of the system to whom the file belongs. Archive

• A collection of contents (files or directories) for backup purpose. Compression

• A technique used for reducing the size of a file or a directory without effecting contents.

Exercise-1:- This exercise shows which types of files are used in linux and how to know bout file types

Linux considers each device as file. There are many types of file that are used in Linux. Use ls –l com-mand to find the type of file. For example:

javidali@JLaptop:/dev$ ls -l

crw-rw----+ 1 root audio 14, 4 2009-04-28 07:01 audio drwxr-xr-x 3 root root 60 2009-04-28 12:01 bus crw--- 1 root dialout 5, 1 2009-04-28 07:01 console lrwxrwxrwx 1 root root 11 2009-04-28 07:01 core -> /proc/kcore

srw-rw-rw- 1 root root 0 2009-04-28 07:01 log brw-rw---- 1 root disk 8, 1 2009-04-28 12:01 sda1 javidali@JLaptop:/dev$

In this example, first character in each row, I.e. the first colom represent the file type. The following table shows file types, representation symbols with short description.

Symbol File type Description

(29)

d Directories Files that act as containers to other files

b Block files Files that are used for block (parallel)devices. Data from such devices are read or written to in blocks.

c Character files Files that are used for character (serial) devices. Data from such de-vices are read or written to character by character

l Symbolic links Shortcut to other files or directories s socket files Files that are used in communication

Regular files other than text files can be explored by using an appropriate program, as indicated in the table below. Follow the command with the name of the file to view it or omit the file name and select the file from the menu once the program is running.

File Type Application Name Command for the application Postscript gv (based on GhostView) gv

Portable Document Format (PDF) Adobe Acrobat Reader acroread Image files XV xv

Image files The Gimp gimp LaTeX ouput (DVI) xdvi xdvi Hypertext (HTML) Netscape Netscape MP3 and MPEG gtv gtv

Exercise-2:- This exercise demonstrates how to view and change access permissions for a file.

We noticed in exercise-1 that ls -l command earlier presented a long of listing file with a line like the following for each file:

-rw-r--r-- 1 root javidali 0 2009-04-28 08:26 newfile.txt

Here the first character in the first column (-) indicates that the file is a normal file. The next 9 characters indicate the access permissions for the file. The next set of 9 characters is divided into 3 groups of 3 cha-racters. Purpose of these characters is as under:

• (-) represents no permission • (r) represents 'read' permission • (w) represents 'write' permission • (x) represents 'execute' permission

The three group represents user (owner of the file), group(to which the owner belongs) and others (any other user of the system) respectively.

Three characters in each group are for 'read', 'write' and 'execute' permission respectively.

In our example, the owner has 'read' and 'write' permission for the file and everyone else has only read permission.

For a normal file, read, write and execute permissions are obvious.

For a directory, read and write permissions mean that to read the contents of the directory and create new entries in the directory. Execute permission means that one can search in the directory but not read from or write to the directory.

(30)

You can use the chmod command to change the access permissions of a file or a directory. To specify permissions for a file with chmod, any of the following two methods can be used.

• use a symbolic mode • use an octal mode

Symbolic mode use combination of the following symbols:

Symbol Meaning

u User

g Group

o Other

a All (equals to ugo)

+ Add a permission

- Remove (take away) a permission

r Read permission

w Write permission

x Execute permission

For example,if the current working directory has the these files:

javidali@JLaptop:~$ ls -l

-rwxr-xr-x 1 root root 955 2009-04-21 08:07 arithmatics.sh -rw-r--r-- 1 javidali javidali 130 2009-04-19 05:29 boidata.txt drwxr-xr-x 2 javidali javidali 4096 2009-04-08 19:56 Desktop drwxr-xr-x 2 javidali javidali 4096 2009-03-12 14:30 Documents

-rwx--- 1 javidali javidali 512000 2009-03-24 18:00 install_v10.70.2.3.tar -rw-r--r-- 1 javidali javidali 750 2009-04-28 08:42 lsresults.txt

-rwxrwxrwx 1 root root 207 2009-04-10 15:55 myscript.sh -rw-rw-rw- 1 root root 208 2009-04-10 15:55 myscript.sh~ -rw-r--r-- 1 student cs 0 2009-04-28 08:26 newfile.txt javidali@JLaptop:~$

Then gives write permission to the group and read permission to others for all files in the current directo-ry, type the command

javidali@JLaptop:~$ chmod g+w,o+r *

Now look at The permissions again:

javidali@JLaptop:~$ ls -l

-rwxr-xr-x 1 root root 955 2009-04-21 08:07 arithmatics.sh -rw-r--r-- 1 javidali javidali 130 2009-04-19 05:29 boidata.txt drwxr-xr-x 2 javidali javidali 4096 2009-04-08 19:56 Desktop drwxr-xr-x 2 javidali javidali 4096 2009-03-12 14:30 Documents

-rwx-w-r-- 1 javidali javidali 512000 2009-03-24 18:00 install_v10.70.2.3.tar -rw-rw-r-- 1 javidali javidali 750 2009-04-28 08:42 lsresults.txt

-rwxrwxrwx 1 root root 207 2009-04-10 15:55 myscript.sh -rw-rw-rw- 1 root root 208 2009-04-10 15:55 myscript.sh~ -rw-rw-r-- 1 student cs 0 2009-04-28 08:26 newfile.txt javidali@JLaptop:~$

Then take away the read and write permission from the owner of the file myscript.sh, group of the owner and all other users for the files newfile.txt, type the command

javidali@JLaptop:~$ chmod a-rw myscript.sh

The result is:

(31)

---x--x--x 1 root root 207 2009-04-10 15:55 myscript.sh

Often your home directory has important documents and needs to restrict access to it. If you want to takes all the three access permissions away from everyone but the user, use the command:

javidali@JLaptop:~$ chmod go-rwx 

Octal mode use the same symbols for user,group and other but for access permissions its uses octal num-bers.

Permission Octal Number Equivalent symbol

Read 4 r--

Write 2 -w-

execute 1 --x

If two or more permissions are to be set, the octal numbers are added together. For example, r-x is equiva-lent to 4+1=5 and rw-r--r-- is equivaequiva-lent to 644. now for example to give read,write and execute permis-sion to user, write permispermis-sion to the group and read permispermis-sion to others for the file mysscript.sh , type the command

javidali@JLaptop:~$ chmod 724 myscript.sh

Here is the result:

-rwx-w-r-- 1 root root 207 2009-04-10 15:55 myscript.sh

To secure your home drive from everyone but the user, use the command:

javidali@JLaptop:~$ chmod 700 

Exercise-3:- This exercise shows how to view and change the own ership of the file

ls -l command is can be used to view the owner of a file. For example to know that who is the owner of the file newfile.txt, issue the following command.

student@JLaptop:~$ ls –l newfile.txt

---x--x--x 1 student cs 207 2009-04-10 15:55 newfile.txt

Here column next to the number '1' represents that 'student' is the owner of this file , and next column in-dicates that group of this owner is 'cs'.

Use chown command to change the owner of a file. For example to change the owner of the file 'newfile.txt' from student to root, issue the following command.

javidali@JLaptop:~$ chown root newfile.txt

The result is:

javidali@JLaptop:~$ ls –l newfile.txt

---x--x--x 1 root cs 207 2009-04-10 15:55 newfile.txt

Note that you have to change the group of the owner as well, for example, to change the owner and group of the file 'newfile.txt' both to root, try the following command.

javidali@JLaptop:~$ sudo chown root:root newfile.txt

The effect will be like:

javidali@JLaptop:~$ ls –l newfile.txt

---x--x--x 1 root root 207 2009-04-10 15:55 newfile.txt

Exercise-4:- This exercise describes the ways to compress/uncompress, files and making archives of files for backup purposes.

(32)

Among many available utilities for archiving and compression purposes are the tar and gzip utilities. tar is an archiving utility while gzip is used for compressing the file size. Compressed files can be restored to their original form using gzip -d or gunzip or zcat. Now for example to backup the 'mydata' directory inside home directory of user 'student', we will first archive the directory and then compress the archive file. Steps are:

javidali@JLaptop:~$ sudo tar -cvf backup.tar /home/student/mydata/ /home/student/mydata/.synaptic/ /home/student/mydata/.synaptic/options . . /home/student/mydata/DriverInstall/sk98lin.tar.bz2 /home/student/mydata/Music/ javidali@JLaptop:~$

We can find that mydata directory and backup.tar file both have the same size. To reduce this size we have to compress the archive. Here is the command;

javidali@JLaptop:~$ gzip backup.tar

Output of this command is a file named backup.tar.gz To uncompress the file again, issue the command

javidali@JLaptop:~$ gzip -d backup.tar.gz

Or

javidali@JLaptop:~$ gunzip backup.tar.gz

Or you can use tar command to uncompress and extract contents of the file. Example is:

javidali@JLaptop:~$ tar -xz backup.tar.gz

Where -z switch issues gzip command from within the tar command and -x switch extract the contents. To list contents of an archive use -t switch with tar command:

javidali@JLaptop:~$ tar -t backup.tar

And to extract the contents of the archive, issue the following command.

javidali@JLaptop:~$ tar -xvf backup.tar Exercises for lab:

Exercise 1:- Change the access permission of to the home directory of your login user to match drwxr-xr-x using both symbolic mode & octal mode.

Exercise 2:- Create a file and modify its access permission so that the file can be executed by user, group and others besides its current permission setting.

Exercise 3:- Create and archive and add all subdirectories of your home directory to that archive.

Home Work:

1) Search the manual page of the utilities gzip and tar and write a procedure to add files and directo-ries to and existing archive.

2) Write a note on the advantages of file level security in operating systems. 3) Why do we often compress files before adding to an archive?

(33)

To understand the command line editors

(34)

Lab No. 05: Command line Text Editors (Vim)

Objective:

To enable students to use command line editors for editing text files. Completing this lab, students will give sufficient knowledge about vim / vi and its features for their daily tasks.

Scope:

On the completion of this lab, you will be able to:

• Start the editor, moving cursor around and exiting the editor. • Work in command mode.

• Copy, Cut and past the text

• format program and check source code • Search Character/string.

• Recover Your Work.

Useful Concepts:

vi

• A screen-based editor used by many UNIX users. • Has a powerful feature to aid programmers. Editing modes

There are two editing modes that the editor can be executed in. • Insert mode

User can type text in this mode • Command mode

User can use commands for operation on the file. (e.g. saving, exiting, searching, etc) Text Buffers in VI

• There are 36 special buffers and also a general purpose buffer for temporary storage of words or. When a block of text is cut from the file it is placed into the general purpose buffer but, if specified, the block of text can also be stored in another buffer. Buffers are numbered from a-to-z and from 0-to-9.

Exercise-1:- This exercise illustrates how to start the editor, move cursor around and exit form the editor.

To start the editor from command line, type

vi

An empty file will be opened in the editor. If you want to open an existing file in the editor, type

vi filename

To switch to 'Insert' mode, press: i key

-- INSERT -- key word at the bottom will indicate that you are in an inserting mode and your cursor will start blinking, to go to the start of the line. Press

(35)

at command mode will take you to the current cursor position and you can enter any text. To move cursor around while you are in command mode, press

h key move left, l key move right, k key move up, j key = move down

you can also use arrow keys while in insert mode to do the same tasks. To switch back to command mode, press

Escape key

While in command mode, each command is preceded by colon ":"

To exit the editor without saving changes made to the file, switch to command mode and type,

:q!

To save changes and exit the editor, switch to command mode and type the command,

:wq

Where "w" is for writing changes to the file and "q" is to quit or exit the editor

Exercise-2:- This exercise illustrates how to Work in command mode in vi edtor.

Press Escape key to switch to command mode and practice the following commands and observe the re-sults.

To replace one character under the cursor, type:

r

to undo the last change to the file. Typing u again will re-do the change.

u

To delete character after the current cursor position

x

Exercise-3:- This exercise illustrates how to Copy, Cut and paste the text

To cut text from the file, type,

d

to cut multiple characters, type:

NUMd

wher NUM is the numper of characters to cut to cut the whole line type:

dd

to cut from current cursor position to the beginning of the line,type.

d^

to cut from current cursor position to the end of the line.

d$

to cut from current cursor position to the end of the word.

Dw

(36)

3dd

You can use the y command which similarly to the d command which is used just to copy the text. To paste the buffer after the cursor position, type:

p

to paste the buffer before the cursor position type:

P

To paste the text for the specified number of times, say 3, before the cursor position, type:

3P

Exercise-4:- This exercise illustrates how to format a program and check source code for

for correctness.

You can use variable to set up the indentation for each level of nesting in code. To set the shift width to 4 characters, type:

:set sw=4

To Shift the current line one shift width to the left, type:

:<<

To Shift the current line three shift width to the right, type:

:3>>

To check for matching parenthesis or brace in your code, place the cursor onto a parenthesis or brace and type:

:%

Exercise -5:- This exercise illustrates how to Search Character/string in a file using vi.

To search a string forwards in the file, say "comsats", type:

/comsats

To search a string backwards in the file, say "comsats", type:

? comsats

To repeat the previous search in the same direction, type:

n

To repeat the previous search in the same direction, type:

N

To search special characters in the file, type a backslash (\) before the character. Some special characters that are used in search expression and their meaning: ^ Beginning of the line. (At the beginning of a search expression) . Matches a single character

* Matches zero or more of the previous character.

$ End of the line, (At the end of the search expression)

[ ] Starts a set of matching, or non-matching expressions... For example: /f[iae]t matches either of these: fit fat fet In this form, it matches anything except these: /a[^bcd] will not match any of these, but anything with an a and another letter: ab ac ad

< > Put in an expression escaped with the backslash to find the ending or beginning of a word. For example: /\<the\> should find only word the, but not words like these: there and other.

(37)

There are two sets of commands used for character search. [f & F] and [t & T] To search for a character forwards within one line, say 'j', type:

/fj

Or

/tj

To search for a character backwards within one line, say 'j', type:

/Fj

Or

/Tj

; or , command can be used to repeat these two sets of commands. ; repeats the last character search command in the same direction, , repeats the command in the reverse direction

Exercise -6:- This exercise illustrates how to recover Your Work:

The VI editor keeps a temporary copy of your edited file, and when you save your work, it puts the con-tents of the temporary copy into the original file. If file is closed accidentally during editing, the VI editor will attempt to save your work for you to recover later.

To recover the file named myfile, start the editor with –r option for recovery

vi -r myfile

and save the recovered file then

Note: The -r option only works once per failed VI session.

Exercises for lab:

Exercise-1: Open a file in vi editor and practice all the commands given below.

^B ^D ^F ^H ^J ^M ^N ^P ^U $ % ^

( ) { } | + - _ 0 B E

G H L M W b e h j k l

w

Note the effect of the options on the output.

Home Work:

1) Practice the following cursor movement commands and write a note on them:

^E ^Y z C

2) Practice the following text replacement commands and write a note on them:

R S c r s

3) Practice the following search commands and write a note on them:

, / ; ? F N T f

n t

4) Practice the following formatting commands and write a note on them: ~ < > J

(38)

To understand the command line file system

(39)

Lab No. 06: Managing the file system

Objective:

To update the students with knowledge about command line file system and partition management.

Scope:

On the completion of this lab, you will be able to recognize: • Pathnames

• Relative/Absolute Paths,

• Path and Environmental Settings,

• Directories vs. Partitions in the File System, • Recognizing/modifying Partitions.

• Understand the bash environment.

Useful Concepts:

Directory

A special type of file that contains other files or directories, same as folders in Windows File system

Like other platforms (Windows, Mac OS etc,), Linux file system is also hierarchical one. Directories can be created inside other directories in a tree-like structure.

Root Directory

The Linux file system tree has only one root, called the root directory, represented by / Sub Directory

A directory inside another directory is usually called a subdirectory. Pathname

Pathname is a sequence of directories to be followed to reach the file. For example, the pathname of the file myfile.txt in the cs user's home directoy is /home/cs/myfile.txt.

Absolute pathnames

A pathname that contains all the information needed to find a file or that start form root directory / is called absolute pathname.

Relative pathname

A pathname that contains information necessary to find a file from a particular point in the tree is called relative pathmane. For example, from the directory /home, the relative pathname of myfile.txt is just cs/myfile.txt. Note that this pathname has no leading /.

Exercise-1:- This exercise illustrates how Multiple Disks in the File system are represented.

Each partition of the disk is mounted at a separate directory in the filesystem. So, for example, a separate disk may be mounted at the directory /mnt. In this case, every time you access something in directory /mnt, you are actually accessing a file on this separate disk. This is transparent to the user, but you can peek at which disks are mounted where on a computer by using the df command in the shell. You will see something like this:

(40)

Filesystem 1k-blocks Used Available Use% Mounted on /dev/hda8 497667 78511 393454 17% /

/dev/hda1 14607 2758 1 1095 20% /boot /dev/hda7 5308207 1085340 3948063 22% /usr /dev/hdc 609750 609750 0 100% /mnt/cdrom

The first line indicates that the disk with symbolic name5 /dev/hda8 is mounted at the root directory. The second line indicates that another disk with symbolic name /dev/hda1 is mounted at subdirectory /boot. The third line is similar.

The disk in the fourth line represents the CD-ROM drive, which is mounted at /mnt/cdrom.

Exercise-2:- This exercise illustrates how to recognize disks.

To see all the disks and partitions on your system, you can list the files in /dev directory. Use ls /dev command will will display all the device related files.

To display only disk related files type:

ls /dev |grep ?d*

output will be something like:

hda1 hda3 hda5 hda7 hdb2 fd0 fd1 sda1 dsa8 sdb2 etc

Here is a brief description of file system names. Disk file name Description

fd0 First floppy disk drive fd1 Second floppy disk drive

hda First master hard disk drive (IDE-0 master) hdb First slave hard disk drive (IDE-0 slave) hdc Second mater hard disk (IDE-1 master) sda First SCSI disk dirve

sdb Second SCSI disk drive

Exercise-3:- This exercise illustrates Recognizing Partitions.

Enter the command

ls /dev |grep ?d*

To display only disk related files and the output will be something like:

hda1 hda3 hda5 hda7

(41)

hdb2 fd0 fd1 sda1 dsa8 sdb2

Disk file name Description

hda1 First master hard disk drive (IDE-0 master), first primary partition hda3 First master hard disk drive (IDE-0 master), third partition

hda5 First master hard disk drive (IDE-0 master), 1st logical partition Hda7 First master hard disk drive (IDE-0 master), 3rd logical partition hdb1 First slave hard disk drive (IDE-0 slave), 1st partition

sda1 First SCSI disk drive, first primary partition. sdb8 Second SCSI disk drive, 4th logical partition

Exercise-4:- This exercise illustrates Mounting/un-mounting partition:

To see the contents stored on a partition you must have a mount point in the root directory from where you can access those contents. To mount a partition, for example hda5 to /mnt directory, type:

mount /dev/hda5 /mnt

Doing this, you will be able to see the content of hda5 partition in /mnt directory. To mount a Windows NTFS partition, type:

mount -ntfs-3g partition_path Mount_point

Un mounting partition, either type:

umount partition Or umount mount_point e.g. umount /dev/hda5 Or umount /mnt

To locate a program file in the user's path, type:

Any of the to command will unmount the mounted partition /dev/hda5 on /mnt

Exercise-5:- This exercise describes Miscellaneous commands: cfdisk Partition table manipulator for Linux export Set an environment variable

fdisk Partition table manipulator for Linux quota Display disk usage and limits quotacheck Scan a file system for disk usage

(42)

Exercises for lab:

Exercise 1:- test all the above exercise and write a note on each exercise. Write the results of the com-mands on successful execution of comcom-mands or the error message on any failure and discuss it with your lab instructor.

Exercise 2:-how many disk and partitions are available on your system? Create a directory in your home directory and mount the first logical partition of your primary hard disk to that directory. Check whether you are able to access the contents of newly mounted file system or not.

Home Work:

1) Define primary partition, extended partition and logical partition. How many primary partitions can you create in a single disk?

2) Search the web and find the procedure of mounting filesystem over the network (remote mount-ing).

(43)

To understand the command line Process Management

(44)

Lab No. 07: Command line Process Management

Objective:

Objective of this lab is to introduce the students with command-line process control and management.

Scope:

The student will be able to know the following at the end of this lab: • Listing Processes

• Ending a Process

• Running a Process in the Background • Changing the process favorability (priority)

Useful Concepts:

Processes

Linux, like most modern operating system, is multitasking, which means that it can execute many pro-grams simultaneously. A program that is currently executing is called a process. A Linux system consists of several dozen active processes at any time.

Some of these processes are system processes that perform important “behind the scenes” tasks and some are user processes corresponding to programs like Netscape or Emacs.

Nice

A process favorability to access the system recourses (processor time) Signals

A special instruction to the process under consideration

Exercise-1:- This exercise illustrates Listing Processes

You can view the processes that are currently running on the system with the ps command. Type ps now and you will see something like the following:

javidali@JLaptop:~$ ps PID TTY TIME CMD 23985 pts/0 00:00:01 bash 24001 pts/0 00:00:00 ps javidali@JLaptop:~$

This tells you that you are running 2 processes and the commands (CMD) used to start them were bash (your shell) and ps (the process you just started when you entered ps). The first column in the list, headed by PID, gives the process ID for each process, an integer used to uniquely identify each process. The next column, TTY, gives the terminal name to which the process is attached. The third column, TIME, gives the amount of time the process has been running for (or the amount of time it has been running since it was last sleeping or stopped).

Using ps by itself only gives information about processes that you own, which, unless you are a system administrator, is usually all the information you need. If you want information about all the processes running on the system, you can issue the ps aux command. This command combines 3 options (the nor-mal dash before options is not necessary) which, together, give information about all processes that have

(45)

users have attached to them. Here is a (significantly trimmed) example of what this output might look like:

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 1324 76 ? S Jul23 0:12 init [5]

root 2 0.0 0.0 0 0 ? SW Jul23 0:21 [kflushd] root 3 0.0 0.0 0 0 ? SW Jul23 0:03 [kupdate] root 4 0.0 0.0 0 0 ? SW Jul23 0:00 [kpiod] root 5 0.0 0.0 0 0 ? SW Jul23 0:14 [kswapd] root 6 0.0 0.0 0 0 ? SW< Jul23 0:00 [mdrecoveryd] root 415 0.0 0.1 1548 160 ? S Jul23 0:02 syslogd -m 0 rpc 440 0.0 0.1 1472 252 ? S Jul23 0:00 portmap root 456 0.0 0.0 0 0 ? SW Jul23 0:00 [lockd] root 500 0.0 0.2 5744 272 ? S Jul23 0:00 [ypbind] nobody 566 0.0 0.0 7616 24 ? S Jul23 0:00 [identd] .

. .

root 1006 14.7 24.7 62796 31612 ? R Jul23 53:50 /etc/X11/X javid 7892 0.0 1.2 7580 1564 ? S 14:15 0:00 gnome-session javid 7957 0.0 1.3 4700 1700 ? S 14:15 1:39 sawmill javid 7966 0.0 2.1 9336 2784 ? S 14:15 3:51 panel javid 7969 0.0 0.8 8404 1092 ? S 14:15 0:00 gmc javid 7972 0.0 0.7 3560 968 ? S 14:15 0:11 xscreensaver javid 7992 0.0 1.3 7676 1676 ? S 14:26 0:21 gnome-terminal javid 7994 0.0 0.6 2440 796 pts/0 S 14:26 0:01 bash javid 12504 0.0 0.1 2004 156 pts/0 S 15:08 0:00 netscape javid 24059 0.0 0.7 2728 900 pts/0 R 15:42 0:00 ps aux

This listing gives a lot of information about the 100 or so processes that are probably currently executing on the system. For example, you can gather that the computer was rebooted last on July 23. You can see that X windows (/etc/X11/X) is using almost 25% of the computer’s memory at the moment and 15% of the CPU time. You can also view the current status (STAT) of each of the processes in the system. An R in this column means that the processing is currently “runnable” which, as you will learn when you take Operating Systems, means that the process is either currently running or in the ready queue, waiting to gain access to the processor. An S indicates that the process is “sleeping” (currently not waiting to use the processor). A W means that, in addition to sleeping, the process has been “swapped out” (not currently resident in memory but on the disk instead). Lastly, the < marks a process that is given higher priority than normal while waiting for the CPU.

Exercise-2:- This exercise illustrates how to terminate a Process

Sometimes you will come across a process that locks up and just won’t quit, no matter what you do. In this case, the only alternative is to force the process to quit. If the process is one that you started from the shell in the foreground, you can end it by typing Ctrl - C. If the process is running in the background, you will need to issue the kill command followed by a process ID. For example, to kill the Netscape process above, you would type:

kill 12504

If this does not work, use the -9 (or -s SIGKILL) option to forcibly kill the process.

The kill command (or Ctrl - C) also comes in handy when you must kill a program that you wrote with an infinite loop!

(46)

Exercise-3:- This exercise illustrates how to Run a Process in the Background

When you run a program in Linux, it can either be run in the foreground or in the background. When you run a program in the foreground (which is the default), the resulting process must finish before you get another prompt in the shell. This is fine when you run short processes like ls, for example. However, if you want to run Netscape (for example) from the shell, you probably do not want to have to quit Netscape in order to get a new prompt to, say, copy a file. The alternative is to run Netscape in the background, which means that the new process will run concurrently with the shellprompt, and a prompt will be re-turned to you immediately. To run a program in the background, simply follow the command with an am-persand (&) character. For example, to run Netscape in the background, type:

netscape &

Generally speaking, any time you run a program that generates its own window on the desktop, it is best to run it in the background.

If you start a program in the foreground by mistake and want to turn it into a background process, hit Ctrl - Z , which suspends the process. Then type

bg

this command restarts the currently suspended process in the background.

Exercises for lab:

Exercise 1:- List all the processes that belong to root user. Exercise 2:- Create a process of gedit and send it to background. Exercise 3:- Change the priority of the process created in exercise no. 2.

Home Work:

1) Find the difference between the output of top utility and ps –aux command.

2) What kinds of signals are used to control a process in UNIX operating system? Where can you find the list of available signals and their numerical values?

(47)

To understand how to writing and executing bash scripts

Lab 8: Basic Bash Scripting, writing and executing

bash scripts

(48)

Lab No. 08: Basic Bash Scripting, writing and executing bash scripts

Objective:

To familiarize students with the basics of bash scripting. How to write and execute bash scripts under the Linux environment.

Scope:

The students would be able to do the following at the end of this lab: • Write Hello world script.

• Usage of Variables, Global vs. Local variables • Passing arguments to the bash script

• Executing shell commands with bash • Reading User Input/ output

Useful Concepts:

Bash

• A UNIX shell as well as an interpreter Script

• A set of instruction (commands) that can be executed on a sell (interprecter).

Exercise-1:- Hello world example. The script declares a string variable, stores “Hello World” in it and finally prints the value of variable on the screen.

#!/bin/bash

# declare STRING variable STRING="Hello World"

#print variable on a screen echo $STRING

Saving and executing the scripts

Save the above script in the file named “hello_world.sh” Navigate to the directory where the script is saved Execute the script using the command “./hello_world.sh”

Exercise -2:- This exercise explains the use of Global vs. Local variables #!/bin/bash

#Define bash global variable

#This variable is global and can be used anywhere in this bash script VAR="global variable"

function bash {

#Define bash local variable

#This variable is local to bash function only local VAR="local variable"

echo $VAR }

echo $VAR bash

# Note the bash global variable did not change # "local" is bash reserved word

(49)

Exercise -3:- This exercise illustrates Passing command line arguments to the bash script #!/bin/bash

# use predefined variables to access passed arguments #echo arguments to the shell

echo $1 $2 $3 ' -> echo $1 $2 $3'

# We can also store arguments from bash command line in special array args=("$@")

#echo arguments to the shell

echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

#use $@ to print out all arguments at once echo $@ ' -> echo $@'

# use $# variable to print out

# number of arguments passed to the bash script

echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'

Passing arguments to the scripts

./arguments.sh Bash Scripting Tutorial

Here ./arguments.sh is the filename and the remaining are the arguments passed to the script.

Exercise -4:- This exercise illustrates Executing shell commands with bash #!/bin/bash

# use backticks " ` ` " to execute shell command echo `uname -o`

# executing bash command without backticks echo uname -o

Exercise -5:- This exercise illustrates Reading User Input #!/bin/bash

echo -e "Hi, please type the word: \c " read word

echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2

echo "Here is your input: \"$word1\" \"$word2\"" echo -e "How do you feel about bash scripting? "

# read command now stores a reply into the default build-in variable $REPLY

read

echo "You said $REPLY, I'm glad to hear that! " echo -e "What are your favorite colours ? " # -a makes read command to read into an array read -a colours

echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"

Exercises for lab:

Exercise 1:- write a shell script that add two numbers and print their sum.

Exercise 2:- write a script that takes a students information as input and print it to the screen.

Home Work:

(50)

2)

To understand the Basic Bash Scripting 1

(51)

Lab No. 09: Advance Bash Scripting 1

Objective:

To familiarize students with the concept of Bash if/else statements, bash loops and bash comparisons.

Scope:

The students would be able to do the following at the end of this lab: • Write shell scripts with conditional execution. • Using loops in bash scripts

Exercise-1:- Simple Bash if/else statement. In this example we declare a variable named di-rectory and assign it a value. Then we check in the if statement that the didi-rectory exists or not and the relevant message is printed on the screen accordingly.

Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work!

#!/bin/bash

directory="./BashScripting" # bash check if directory exists if [ -d $directory ]; then

echo "Directory exists" else

echo "Directory does not exists" fi

Exercise -2:- This exercise demonstrates Bash “for” loop #!/bin/bash

# bash for loop

for f in $( ls /var/ ); do echo $f

done

Exercise -3:- This exercise demonstrates Bash while loop #!/bin/bash

COUNT=6

# bash while loop

while [ $COUNT -gt 0 ]; do

echo Value of count is: $COUNT let COUNT=COUNT-1

done

Exercise -4:- This exercise demonstrates Bash until loop #!/bin/bash

COUNT=0

# bash until loop

until [ $COUNT -gt 5 ]; do

echo Value of count is: $COUNT let COUNT=COUNT+1

done Exercises for lab:

Exercise 1:- write a shell script that inputs two numbers from the user and check if they are equal or not Exercise 2:- write a script that takes a number input from user and print its table.

(52)

Home Work:

1) Write a script that takes a number input from user and calculate its factorial.

(53)

To understand the Advance Basic Bash Scripting 2

(54)

Lab No. 10: Advance Bash Scripting 2

Objective:

To familiarize students with the concept of arrays in bash scripting, bash functions and bash file test-ing/handling.

Scope:

The students would be able to do the following at the end of this lab: • Write shell scripts that make use if arrays.

• Use functions in their shell scripts.

• Use various file testing options in their code

Useful Concepts:

Bash File Testing Options

-b filename Block special file -c filename Special character file

-d directoryname Check for directory existence -e filename Check for file existence

-f filename Check for regular file existence not a directory

-G filename Check if file exists and is owned by effective group ID. -g filename true if file exists and is set-group-id.

-k filename Sticky bit -L filename Symbolic link

-O filename True if file exists and is owned by the effective user id. -r filename Check if file is a readable

-S filename Check if file is socket -s filename Check if file is nonzero size -u filename Check if file set-ser-id bit is set -w filename Check if file is writable

-x filename Check if file is executable

Exercise -1:- This exercise demonstrates how to Declare simple bash array

#!/bin/bash

#Declare array with 4 elements

ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux ) # get number of elements in the array

ELEMENTS=${#ARRAY[@]}

# echo each element in array # for loop

for (( i=0;i<$ELEMENTS;i++)); do echo ${ARRAY[${i}]}

done

(55)

#!/bin/bash #Declare array declare -a ARRAY

#Open file for reading to array exec 10<bash.txt

let count=0

while read LINE <&10; do ARRAY[$count]=$LINE ((count++))

done

echo Number of elements: ${#ARRAY[@]} # echo array's content

echo ${ARRAY[@]} # close file exec

10>&-Exercise -3:- This exercise demonstrates Bash Functions !/bin/bash

# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER function function_B { echo Function B. } function function_A { echo $1 } function function_D { echo Function D. } function function_C { echo $1 } # FUNCTION CALLS

# Pass parameter to function A function_A "Function A."

function_B

# Pass parameter to function C function_C "Function C."

function_D Exercises for lab:

Exercise 1:-Write a shell script that inputs a file name as string from user and check if any file with this exists or not.

Exercise 2:- Write a shell script that reads the contents of a text file and count the number of words in the file. Implement the feature of counting the words in a separate function.

Home Work:

1) Write a shell script that copies a single file to all directories in the tree of the root filesystem using recursion.

(56)

To understand the gcc

(57)

Lab No. 11: Introduction to gcc

Objective:

Objective of this lab is to familiarize the student with the GNU C compiler.

Scope:

The student will be able to know the following at the end of this lab: • Use command line editor to write a C/C++ program • Compile a/C++ C program

• Make a program

• Debug and execute a C/C++ program

Useful Concepts

gcc

A command line GNU C compiler g++

A command line C++ compiler Compiling

A process of converting source code to object code Make

• A utility used to manage large projects involving different files

• Out put is a makefile that describes the files involved in the project and the dependencies between them

Debugging

• Process of removing logical errors form the code

• GNU DDD (Data Display Debugger) is a debugger with a more sophisticated interface that, among other things, incorporates an interactive graphical data display feature, where data structures are displayed as graphs.

Exercise-1:- This exercise demonstrates Writing a C Program in linux test editors.

To write a C program, you can use any editor. Linux has a rich set of Code-oriented GUI Editors (with syntax highlighting, indentation, etc.) i.e. glimmer, nedit, gvim, kwrite, and xemacs etc. But if you are using the command line, you can try vim or emacs editor, we will use vim in our example.

Type the following on command prompt. Vim introprogram.c

And you will have an empty file opened in the vim editor if the file intoprogram.c does not exist before. Press I key to switch to insert mode and type the following program:

#include<stdoi.h> #include<stdio.h> Int main ()

(58)

Printf("\n welcome to gcc tutorial"); Return 0;

}

Hit ESC key to switch back to command mode and type

:wq

to save the program and exit the editor.

Exercise-2:- This exercise demonstrates Compiling Programs

You can learn more about g++ later by looking at the man pages. (There’s a lot there!) For now, we’ll just look at the basics.

To compile the C program of exercise 1, in the shell, simply type

gcc -o intro_program introporgram.c

in the terminal window. The -o option gives the name of the executable to create; if omitted, the executa-ble will be called a.out.

In general you’ll probably want to compile programs with more options specified. Here is a better way to compile a program:

gcc -g -Wall -o intro_program introporgram.c

The -g option produces debugging information in the executable. The -Wall option instructs the compile to display “all warnings

To compile multiple source files into one executable, just include them all on the command line. For ex-ample, to compile

Prog1.c and prog2.c into a single executable called prog, type:

gcc -g Wall -o prog prog1.c prog2.c

Once you have a working executable program, go to a terminal window to execute it. Make sure you are in the correct directory and then type the name of the executable program.

Exercise-3:- This exercise explains the used of Make utility

When you are creating large software projects, it is usually a good idea to break the code into multiple source files. This way, errors are usually easier to find and edit, and when you recompile the program you only need to recompile the file you changed and those upon which it depends. Of course, this can become confusing and complicated when the system becomes large. Linux has a powerful tool called make that allows you to efficiently manage a complex project and compile it efficiently. The make utility reads a file called a makefile that describes the files involved in the project and the dependencies between them. Each line in a makefile is of the form:

targets: dependencies <Tab> commands

Here, targets is a list of target files separated by spaces and dependencies is a list of files on which the targets depend. In other words, if any of the files in a dependency list is modified, make should recompile and/or relink the target. The commands are the commands used to recreate the targets. (Note that the <Tab> preceding commands really must be a tab character and not several spaces.)

For example, consider the following simple makefile:

(59)

sort: sort.o list.o g++ sort.o list.o -o sort sort.o: sort.cc sort.h g++ -g -c sort.cc list.o: list.cc list.h g++ -g -c list.cc

This file states that the executable sort is dependent on the object files sort.o and list.o. If either of these object files change, the command g++ sort.o list.o -o sort should be used to recreate (link) sort from the object files. The next two groups show how to create the object files. The first states that sort.o should be recreated (compiled using g++) if sort.cc or sort.h changes. (The -c option to g++ tells the compiler to only compile, creating object files, and not to link them together.) The third group does a similar thing for list.o. So, you can see that if, for example, list.h is modified,

list.o and then sort will need to be recreated but sort.o will not.

To use this makefile, it should be placed in the same directory as the source files and named Makefile. Then, execute make sort to compile and link everything.

Exercise-4:- This exercise demonstrates the Debugging process.

You can start up DDD by typing ddd in the shell, followed by the name of your executable program. In order for the source program to be visible to the debugger, you had to have compiled the program with the -g option, which includes debugging information in the executable. To simply run your program in DDD, press the Run button in the small floating window that appears. The output of your program will be dis-played in the window below your source code. The Interrupt button will stop a running program, the same way a Ctrl - C does in the shell. If you want to continue to run your program from where you left off, press the Cont button. Usually, when you are debugging a program, you want the program to stop execu-tion at some point so that you can examine the value of a variable or check some other part of your pro-gram. To stop your program, you set a breakpoint. To set a breakpoint, find the line of your source code where you wish to stop and click to the left of it with the left mouse button. Then press the Break button (with the stop sign) below the menu bar. A stop sign icon should appear to the left of the line. Now, when you run your program, execution will stop every time this line is reached. You can set as many break-points as needed. To clear a breakpoint, do the same thing, except this time the stop sign will be dimmed and the button will say Clear instead.

If you wish to have your program stop every time the value of some variable changes, you can set a watchpoint. To set a watchpoint, left-click on a variable name in your source code and press the Watch button below the menu bar.

Once your program has stopped, there are two options (buttons) for stepping through your program a line at a time — Step and Next. To step means to proceed to the next line of source code in your program, even if it is inside a function. The Next option advances to the next source line, but treats function-calls as if they were single instructions. The Stepi and Nexti buttons behave similarly, but recognize individual machine language instructions, not lines of source code.

To view the value of a variable as your program runs, select that variable name by left-clicking on it and then press the Display button below the menu bar. A box with that variable’s value will appear in a new window above your source code.

(60)

These are the basics of DDD. But there is quite a bit more to learn if you desire. The display function of DDD, in particular, is quite sophisticated and flexible. Under the Help menu, you can find context sensi-tive help and a detailed manual (also available at w.gnu.org/manual/ddd/). You will also notice that if you linger over a button with the cursor, a description of that button will appear.

Exercise-5:- This exercise demonstrates the Execution of a program

To execute the program form the terminal window or a shell, type the name of the executable file (the output file of compiling process). For example, to run the program of exercise 1, type.

./introprogram

Where ./ is te relative path of the executable file named introprogram.

You can also use the ablolute path to execute a program or add the directory to the users search path in-order to execute the program without referring path.

To use absolute path, for example your executable file is located at /home/cs, type:

/home/cs/introprogram

To at the directory cs to users search path, first type

Export PATH=$PATH:/home/cs

And then to run the program now just type

introprogram Exercises for lab:

Exercise 1:- Write a C program that display your name and registration number using vim editor Exercise 2:- Compile the program using a default output file name a.out

Exercise 3:- debug the program using ddd debugger.

Home Work:

1) Go to the manual page of gcc and g++ and find the difference between them 2) Practice the different options available with gcc talked about in gcc's manual bage.

(61)

To understand the Basic Linux Networking 1

References

Related documents

In the simplest scheme based on the boolean model for retrieval, we retrieve the documents that have occurrences of both good and teacher.. Such

A wide range of pipe materials is available for installation using pipejacking and microtunnelling techniques, the choice depending on the requirements of the client, the

WordNet [14] is an electronic lexical database for English which stores lemmas and exceptional forms of words, word senses, sense glosses, semantic and syntac- tic relations

Reception: Includes a five hour reception, round guest tables, gold chavari chairs, gift, guest book and cake table, white tablecloths and white napkins, glassware, silverware,

However, even if inflation truly was ’always and everywhere a monetary phe- nomenon’ in the long run, as stated by Friedman in his seminal 1963 book, a conventional vector

[r]

TPU Educational Standards-2010 develop and supplement FSES requirements with those of international certifying and registering organizations (EMF, APEC Engineer

Considering a range of tax and benefit systems, particularly those having benefit taper rates whereby some benefits are received by income groups other than those at the bottom of