unit ii-programming in linux

39
Dr.Y.Narasimha Murthy.Ph.D [email protected] UNIT-II : PROGRAMMING IN LINUX Overview of UNIX : UNIX was developed by KenThomson and Denis Ritchie in early 1969.It became an popular in academic community in 1970s and commercialized in 1981.Now it is used in both academic and commercial areas. UNIX is a multi user operating system developed in high level language i.e C,unlike earlier operating systems which were developed in assembly language. The UNIX operating system is made up of three parts - the kernel, the shell and the programs. The kernel : The kernel of UNIX is the central part of the operating system .It allocates time and memory to programs and handles the file store and communications in response to system calls. The kernel and shell always work together. For ex: Type the command rm myfile , then the shell searches the file store for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands. The shell : The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The 1

Upload: murthy-yn

Post on 06-May-2015

1.489 views

Category:

Technology


0 download

DESCRIPTION

This class notes is meant for M.Sc(Ele&Commun) II-semester students of SKU and other universities

TRANSCRIPT

Page 1: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

UNIT-II : PROGRAMMING IN LINUX

Overview of UNIX : UNIX was developed by KenThomson and Denis Ritchie in early 1969.It

became an popular in academic community in 1970s and commercialized in 1981.Now it is used

in both academic and commercial areas.

UNIX is a multi user operating system developed in high level language i.e C,unlike earlier

operating systems which were developed in assembly language.

The UNIX operating system is made up of three parts - the kernel, the shell and the programs.

The kernel : The kernel of UNIX is the central part of the operating system .It allocates time and memory to programs and handles the file store and communications in response to system calls.

The kernel and shell always work together. For ex: Type the command rm myfile , then the

shell searches the file store for the file containing the program rm, and then requests the kernel,

through system calls, to execute the program rm on myfile. When the process rm myfile has

finished running, the shell then returns the UNIX prompt % to the user, indicating that it is

waiting for further commands.

The shell :

The shell acts as an interface between the user and the kernel. When a user logs in, the login

program checks the username and password, and then starts another program called the shell.

The shell is a command line interpreter (CLI). It interprets the commands the user types in and

arranges for them to be carried out. The commands are themselves programs: when they

terminate, the shell gives the user another prompt (% ).

The expert user can customize his/her own shell, and users can use different shells on the same machine.

The shell keeps a list of the commands you have typed in. If you need to repeat a command, use the cursor keys to scroll up and down the list or type history for a list of previous commands.

1

Page 2: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Files and processes :

Everything in UNIX is either a file or a process. A process is an executing program identified by

a unique PID (process identifier). A file is a collection of data. They are created by users using

text editors, running compilers etc.

All the files are grouped together in the directory structure. The file-system is arranged in a

hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root

(written as a slash / ).

Other important processes are the file management (rm , cat , ls , rmdir , mkdir), user

management (passwd, chmod, chgrp), process management (kill, ps), printing (lp, troff, pr) and

program development tools

In the diagram above, we see that the home directory of the undergraduate student "EleIISem" contains two sub-directories (docs and pics) and a file called report.doc.

The full path to the file report.doc is "/home/its/ug1/EleIISem/report.doc"

To open an UNIX terminal window, click on the "Terminal" icon from Applications/Accessories menus.

2

Page 3: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

An UNIX Terminal window will then appear with a % prompt, waiting for you to start entering commands.

Features of UNIX :

i. It is a Multi-user O.S - more than one user can use the machine at a time supported via

terminals (serial or network connection).

ii.It supports Multi-tasking - more than one program can be run at a time.

iii.It has hierarchical directory structure, to support the organization and maintenance of files.

iv. It is highly portable -only the kernel ( <10%) written in assembler. This means that the

operating system could be easily converted to run on different machines.

v. A wide range of support tools (debuggers, compilers) are available.

Processes : Each program running on a UNIX system is called a process. When a user types a

command, UNIX constructs a Process Control Block (PCB) for the process that processes. Each

process has a PCB that holds its priority, the process state, register information and additional

details.

UNIX provides a set of utilities for managing processes.The commands for process are

ps : list processes kill : kill a process & : run a process in the background

If the system administrator found that a particular user was performing an operation that was

consuming too much computing time or dominating a system resource such as a printer, they

could use the ps command to identify the offending user’s process and then use the kill

command to terminate that process.

Each program is assigned a priority level. Higher priority tasks (like reading and writing to the

disk) are performed more regularly. User programs may have their priority adjusted dynamically,

upwards or downwards, depending upon their activity and available system resources.

Multi-tasking systems support foreground and background tasks. A foreground task is one that

the user interacts directly by using the keyboard and screen. A background task is one that runs

in the background (it does not have access to the screen or keyboard). Background tasks are

usually used for printing.

3

Page 4: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Differences between DOS and UNIX :

i.Unix is multi user and multi tasking operating system whereas DOS is single user, single task

system.

ii. All the commands in Unix should be given in lower case while the DOS commands are case

insensitive.

iii. Unlike Unix, DOS is more virus prone.

iv. Processor will be in protected mode in Unix whereas DOS uses unprotected mode.

v. DOS uses only 640KB of RAM during boot time where as Unix which uses all the available

RAM.

vi. Unix needs an administrator which is not the case with DOS.

vii.Unix employs time sharing operating system. Where as DOS supports a pseudo time sharing

known as Terminate and Stay Resident (TSR) programs.

viii.Unix supports both character user interface and graphical interface (X Windows) unlike

DOS which supports only character user interface.

ix. User requires legal username and password to use Unix machines. DOS systems can be used

by any one without any username and password.

x. Unix uses single directory tree (/) irrespective of how many drives or partitions are there.

Where as in DOS, a separate directory tree exists for each partition.

xi. Unix supports NFS to share files.

LINUX OVERVIEW : Linux is a multitasking, multiuser operating system, which means that

many people can run many different applications on one computer at the same time. Linux was

developed by Linus Trovalds at the university of Helsinki ,Finland in August. 1991.It is a freely

distributed implementation of UNIX like kernel

Popular variants of LINUX are Ubuntu, Red Hat, Debian, SuSE , Caldera Mandrake , Corel

Slackware and TurboLinux etc.

Since the LINUX is a multi user operating system,every user is given a username or login

name.The system administrator logs in as a root.A number of users can form a group and each of

these groups is given a name.

Components of Linux : The two important components of LINUX are Shell and Kernel

4

Page 5: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Shell : Shell is the command interpreter which reads the program typed at the terminal

[normally at ($) sign ] , line by line and perform the required operations.

The shell is the part of Linux O.S that acts as an interface between user and the O.S.

It develops a shell around the system that converts our instructions into commands, which

helps the system to understand and act on it.

Linux system provides every user its own copy of shell program which makes him work freely without any interference of other users.

Kernel : The other component of the Linux O.S is the kernel which makes a direct interface with the hardware components.

The kernel make creation and deletion of processes, schedule the memory management and I/O management of the processor.

It provides a mechanism for synchronization of processes so that processes synchronize their actions.

It provides mechanism for inter process communication.

The Linux kernel is composed of five main subsystems

5

Page 6: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

The process scheduler controls the process access to CPU, as it enforces a policy to ensure a fair access, while ensuring that necessary hardware actions are performed by the kernel on time.

The Memory Manager (MM) allows multiple processes to securely share the machine's main memory system. It also supports virtual memory that allows processes to use more memory than is available in the system. With the use of file system, unused memory is swapped out to persistent storage and swapped in when required.

Virtual File System (VFS) presents a common file interface to all devices and abstracts the details of the variety of hardware devices. The VFS also supports many file system formats that are easily compatible with other operating systems.

The Network Interface (NET) provides access to several networking standards and a variety of network hardware.

The Inter-Process Communication (IPC) subsystem process-to-process communication on a single Linux system.

The Kernel Subsystem Overview in the above diagram shows a high-level decomposition of the

Linux kernel, where lines are drawn from dependent subsystems to the subsystems they depend

on. It is clear from the diagram that the process scheduler is the most central subsystem. All

other subsystems are dependent on it since all subsystems need to suspend and resume processes.

Comparison between LINUX and UNIX

FEATURES LINUX UNIX

Hard disk space required 150 MB 500MB

LICENSING General Public Licensing(GPL) Paid Licensing

Variants Red Hat,Ubuntu,Debian,Linux

PPC, Caldera

Sun-Solaris, AT&T, Ultrix,

Minix

6

Page 7: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Editors:

To edit or modify the shell's startup files, as well as most of the other configuration files on the

system, a program called a text editor is used. So, a text editor is required to create a text file or

a C/C++ or any other program. This text editor will help to create the text file ,edt it to correct

the errors and also helps to save the file with suitable extensions in any memory location. There

are various editors available to create the files or programs. The important editors are ed and Vi.

The ed is a line editor ,which can edit one line at a time and the Vi(Visual mode) is a screen

editor ,in which the user can move freely around the screen and edit text at any point

All text editors can be invoked from the command line by typing the name of the editor followed

by the name of the file you want to edit.

For example $ gedit , invokes the ed line editor.

Another editor $ vi :invokes a text editor

Directory Commands :

The Linux system , n login gives a default directory called Home directory and it is denoted by

Home.All the files are stored in this directory . Any number of sub-directories can be created

within this directory. Each sub-directory can be used for different files like C-files or Java-Files

etc..

To create a subdirectory the command mkdir <filename> is typed at the terminal.(make

directory)

For example to create a sub-directory SSBN ,simple type

$ mkdir SSBN and press enter. This will create a subdirectory by name SSBN in the Home

directory.

To view this sub directory type ls at the $ terminal. It displays all the files/directories on the

screen.

To move to the parent directory from the subdirectory ,type cd.. (Change directory) at the $

terminal .Here the dots following

For example $cd.. will move to the parent directory .

To know the present working directory type pwd (present working directory) at the $ terminal.

Ex: $ pwd ,it will display the name of the present working directory.

7

Page 8: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

To search a file use the command find at the $ terminal.

Ex: $find

The command df is used to know the disk space occupied by the total file system.

Some basic directory commands are given in table below

Input/Output redirections: The method of changing the standard inputs or outputs to other

inputs like files is known as I/O redirections.

In any system the standard input is the keyboard and it is considered as stdin. Similarly the

standard output is the monitor and it is abbreviated as stdout. The error messages are displayed

on the monitor ,abbreviated as stderr.

In Linux all devices are treated as files. So, there are three standard files .(i) stdin (ii) stdout (iii)

stderr.

So,some times the input may be taken from a file.and the output may be redirected to a file.

The redirection commands are

$ ls -1> filelist

$cat filelist

The first command will display the contents of the directory.But instead of displaying on the

monitor it will sent the contents to a file named “filelist”.Using the second command the contents

of the file can be seen.

8

Page 9: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

So,here the output is redirected to a file instead of the monitor.

The output redirection is done using the symbol “ > “ . The ">" takes standard output and

redirects it to a file

The instruction $cat file2>>file1 will append file1 and file2 of the directory.

Sometimes the input can also be taken from a file instead of stdin .For this use the command

$ wc < filename .This is the input indirection and the symbol used is “<”

Both the input indirection and the output redirection can be combined into one command.

$wc <file1>file2.

This command will read the contents of the file1 , perform word/line/character count and the

counts are put in file2.

Pipes and Filters:

A pipe sends the output of one program to another program as input. A filter is a special kind of

pipe that processes a stream of input data to yield a stream of output data.

A filter processes another program’s output, altering it as a result. The filter’s output then

becomes input to another program.

In shell programming, a pipe is a way to connect the output of one program to the input of another program without any temporary file.

The piping operation is denoted by the symbol vertical line │.The meaning is the standard output

of the command to the left of the pipe gets sent as standard input of the command to the right of

the pipe.

For example the command $cat ex1.c will display the file ex1.c in one shot. Suppose the file

ex1.c is a very long file , the user can see only the last few lines on the monitor. So, to see the

entire file, use the command $cat ex1.c│more to display more lines.

Here the output of the cat command is passed to the more command which displays few more

lines at a time.

Another example is $ cat weather.txt | wc , the cat command is used to display the contents of

the weather.txt file, but the display is not sent to the monitor , it goes through a pipe to the wc

(word count) command. The wc command then does its job and counts the lines, words, and

characters of what it got as input.

 A filter takes the standard input, does something useful with it, and then returns it as a standard

output.So, a filter performs some kind of process on the input and gives output.

9

Page 10: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Linux has a large number of filters. Some useful ones are the commands awk,  grep,  sed (stream

edit),  spell, and  wc.

Ex1: $ grep -v "^d"

The filter grep removes any directories from the list by excluding any lines that start with a leading "d":

Ex2: $ awk '{print $5, $8, $3, $6, $7}'

The filter awk extracts the required fields (file name, user name, access date and time, and file

size). It also places the file size at the start line so that the data is ready for sorting :

Ex 3: $ sort -nr

This filter sorts the data .

Ex 3: $ tr [a-z] [A-Z] Convert everything to uppercase

Similarly, in the command $ more filename , more is a filter that processes the input data to

display a few lines at a time. The important filters that can be used directly as the commands or

that can be used through the pipe operation are

$ tr : Translation utility.

$ Prep: file splitting utility

$ ls |sort :This command will sort the contents of the directory.

$ ls | sort –r :This command sorts the contents of the directory in reverse alphabetical order.

$sort –n filename : This command sorts the numbers in a file.

File Protection:

Linux is a multitasking, multiuser operating system, which means that many people can run

many different applications on one computer at the same time.So, security of user and system

data is very important. Access should be given only to users who need to access the data. Linux

provide , good and efficient file security . There are various commands available in LINUX to

add additional permissions to a file. So that a file is protected from occasional errors like deletion

,corruption etc.

For example the command d rwx r-x --- has 9 characters. Here d indicates the directory.The

next 9 characters define the file permissions. These permissions are given in groups of 3 each.

The first 3 characters are the permissions for the owner of the file or directory. The next 3 are

10

Page 11: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

permissions for the group that the file is owned by and the last 3 characters define the access

permissions for everyone who do not belong to the group.

There are 3possible attributes that make up file access permissions.

r - Read permission. Whether the file may be read. In the case of a directory, this would mean

the ability to list the contents of the directory.

w - Write permission. Whether the file may be written to or modified. For a directory, this

defines whether you can make any changes to the contents of the directory. If write permission is

not set then you will not be able to delete, rename or create a file.

x - Execute permission. Whether the file may be executed. In the case of a directory, this

attribute decides whether you have permission to enter, run a search through that directory or

execute some program from that directory.The read ,write and execute bits are set to 1 or 0

depending on whether the permission is granted or not.

To change the permissions ,the command chmod is used.

For ex: $ chmod 644 file name, denotes that read and write permissions are granted to owner

only, read permission is granted only to group members and others.

Similarly $chmod 777 filename denotes that ,the read,write and execute permissions are given to

everyone.

Also the command with –t,-w,-x Or +t, +w, +x options indicate denial of permission to – and

granting permission to +.

Process Commands:

Process is any kind of program or task carried out by the PC. For e.g. $ ls -lR , is command or a

request to list files in a directory and all subdirectory in the current directory. It is a process.

A process is program (command given by user) toperform some Job. In Linux when you start

process, it gives a number (called PID or process-id), PID starts from 0 to 65535.

When a system starts up, the kernel initiates a few of its own activities as processes and launches

a program called init. init , in turn, runs a series of shell scripts (located in/etc) called init scripts,

which start all the system services. Many of these services are implemented as daemon

programs, programs that just sit in the background and do everything without having any user

interface. So even if we are not logged in, the system is at least a little busy performing routine

11

Page 12: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

stuff. The fact that a program can launch other programs is expressed in the process scheme as a

parent process producing a child process.

Each process is assigned a number called a process ID or PID. PIDs are assigned in ascending

order, with init always getting PID 1. The kernel also keeps track of the memory assigned to

each process, as well as the processes' readiness to resume execution. Like files, processes also

have owners and user IDs, effective user IDs, etc.

So, in LINUX system ,when the user first logs in ,a process is created, which is the shell. Once a

command is entered ,the shell creates another process.The shell process is the parent process and

the command process is the child process.

Each process is identified by a unique number called process ID(PID).Each PID is associated

with a PPID, i.e Parent Process ID.

So,a process is a part of execution in a Linux system.

For example the command $ ls ,will list out all the directories or files.So,this is a process which

is executed by your kernel.

The most commonly used command to view processes (there are several) is ps.To know the

various processes running on Linux system the command $ ls –ef is used.

In the output displayed on the monitor, one can find the PID,PPID and the time of creating the

process,and the command given.

For example let us consider the command $ ps ,

On the monitor ,the following is displayed

PID TTY TIME CMD5198 pts/1 00:00:00 bash10129 pts/1 00:00:00 ps

Here in the result two processes are found., process 5198 and process 10129, which are

bash and ps respectively. TTY is short for “Teletype,” and refers to the controlling terminal for

the process. Unix is showing its age here. The TIME field is the amount of CPU time consumed

by the process.

Suppose the process under execution is to be stopped due to any reason.Then the command kill

is used. The command kill sends a signal to the process for termination.

12

Page 13: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

$kill -9 <pid> here <pid> is replaced by the process ID using the process $ps –ef command.

Normally the system administrator can kill any process , the user is not authorized to kills others

processes. He can only kill his processes.

The kill command doesn't exactly “kill” programs, rather it sends them signals. Signals are one

of several ways that the operating system communicates with programs.

Signals: A signal is a condition to generate an event by Linux system. Suppose the Del key is

pressed during the execution of a program ,it means that you are sending a signal to the process

to terminate execution abruptly.

So, signals are one of several ways that the operating system communicates with programs. One

can see the action of signals with the use of Ctrl-c and Ctrl-z. When the terminal receives one

of these keystrokes, it sends a signal to the program in the foreground. In the case of Ctrl-c, a

signal called INT (Interrupt) is sent ; with Ctrl-z, a signal called TSTP(Terminal Stop) .

Programs, in turn, “listen” for signals and may act accordingly as they are received.

Ex1: $ TERM : Terminate. This is the default signal sent by the kill command. If a program is

still “alive” enough to receive signals, it will terminate.

Ex2: KILL : Kill. Here the kernel immediately terminates the process. When a process is

terminated in this manner, it is given no opportunity to “clean up” after itself or save its work.

For this reason, the KILL signal should only be used as a last resort when other termination

signals fail.

Ex3: $ STOP : Stop. This signal causes a process to pause without terminating. Like the KILL signal, it is not sent to the target process, and thus it cannot be ignored.

Introduction to Shell : A shell is an interface between the user and the operating system.It is

not an operating system ,but it is simply a C program which provides the interface between

the user and the OS. It interprets each command and takes necessary action. When a command is

entered by the user , the shell will search for the command in /bin and then /usr /bin/ and then

the current directory. So, Shell is a command language interpreter that executes commands read

from the standard input device (keyboard) or from a file. (In MS-DOS, Shell name is

COMMAND.COM which is also used for same purpose) .

Linux use one of the following most popular Shells.

13

Page 14: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Name of the Shell Developer Developed at Remarks

BASH ( Bourne -Again SHell )

Brian Fox and Chet Ramey

Free SoftwareFoundation

Most common shell in Linux. It's Freeware shell.

CSH (C SHell) Bill Joy University of California(For BSD)

The C shell's syntax andusage are very similar to the C programming language.

KSH (Korn SHell) David

Korn

AT & T Bell Labs -----------

Any of the above shell reads command from user (via Keyboard or Mouse) and tells Linux O/s

what users want. If commands are from keyboard it is called command line interface ( Usually

in-front of $ prompt, This prompt is depend upon the shell and Environment that is set or by the

System Administrator, therefore you may get different prompts ).

To find the shell type following command is used $ echo $SHELL.

Variables in Linux : The data to be processed is stored in the RAM location of the computer.

This RAM is normally divided into small locations and denoted by a unique name .This unique

name given to the memory locations is called memory variable or simply variable.

In Linux, there are two types of variables

(i) System variables and (ii) User defined variables (UDV)

The system variables are created and maintained by Linux itself. This type of variable defined

in CAPITAL LETTERS.

User Defined variables are - Created and maintained by user. This type of variable defined in

lower LETTERS.

A list of system variables are given below.

S.No System Variable Meaning

1 BASH=/bin/bash Our shell name

2 BASH_VERSION=1.14.7(1) Our shell version name

3 COLUMNS=80 No. of columns for our screen

4 HOME=/home/murthy Our home directory

5 LINES=25 No. of columns for our screen

6 LOGNAME=students Our logging name

14

Page 15: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

7 OSTYPE=Linux Our o/s type :)

8 PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings

9 PS1=[\u@\h \W]\$ Our prompt settings

10 PWD=/home/students/Common Our current working directory

11 SHELL=/bin/bash Our shell name

12 USERNAME= murthy User name who is currently login to this PC

User Defined variables (UDV):

The syntax for UDV is variablename=value

Here 'value' is assigned to given 'variablename' and Value must be on right side = sign

For Ex: $ no =10 # this is correct

But $ 10 = no # Is error, NOT Ok, because Value must be on right side of = sign.

To define variable called 'veh' having value Bus

$ veh = BusTo define variable called n having value 10 we write $ n=10Rules for Naming variable name (Both UDV and System Variable) :

(i).Variable name must begin with Alphanumeric character or underscore character( _ ) ,

followed by one or more Alphanumeric character. For e.g. Valid shell variable are as follows

HOMESYSTEM_VERSIONvehno.

(ii).Spaces are not allowed on either side of the equal sign when assigning value to variable. For e.g.. In following variable declaration there will be no error$ no=10But in the following , commands error will occur.$ no = 10$ no= 10$ no = 10

(iii) Variables are case-sensitive, just like filename in Linux. For example.$ no=10$ No=11$ NO=20

15

Page 16: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

$ nO=2

All, the above are different variable names.

(iv).NULL variable is defined as follows (NULL variable is variable which has no value at the time of definition) For example (i) $ veh =(ii). $ vech = ""

(v) Do not use ?,* etc, to name your variable names.

Writing shell script :

To write shell script one can use any of the Linux's text editor such as vi or gedit or even

you can use cat command.

Type following program using cat command

$ cat > first#

# My first shell script

#

clear

echo " LINUX is very useful"

Press Ctrl + D to save.

Now the script is ready.

To execute it type command

$ ./first

This will give error since Execute permission are not set for the script .So , to do this type

$ chmod +x first and $ ./first .Now on execution First screen will be clear, then LINUX is very useful is printed on

screen.

Shell Programming Costructs:

The shell programming language has several constructs that give added flexibility to the programs. They are (i) Comments (ii) here command (iii).exit (iv) looping construct (v).Conditional construct (vi) breakComments :

When comments are placed in a shell program, the shell ignores all text on a line following a

word that begins with a ``#'' (pound) sign. If the ``#'' sign appears at the beginning of a line, the

comment uses the entire line; if it appears after a command, the command is executed but the

16

Page 17: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

remainder of the line is ignored. The end of a line always ends a comment. The general format

for a comment line is #comment.

For example, a program that contains the following lines will ignore them when it is executed:

# This program finds factorial

# This program needs a password

Comments are useful for documenting the function of a program and should be included in any

program you write.

Here documentsA here document allows to place into a shell program lines that are redirected to be the input to a

command in that program. By using a here document, you can provide input to a command in a

shell program without using a separate file. The notation consists of the redirection symbol ``<<''

and a delimiter that specifies the beginning and end of the lines of input. The delimiter can be

one character or a string of characters; the ``!'' is often used.

Ex: $ cat gbday mail $1 <<! Best wishes to your exams. ! $

Exit:

The exit command terminate a program at a point other than the end of the program and use

return codes.Most shell commands issue return codes that show whether the command executed

properly. By convention, if the value returned is 0 (zero), then the command executed properly;

any other value shows that it did not. 

For Ex: $ cat hello

This is file hello. $ echo $? 0 correctly executed $ cat hella cat : cannot open hella $ echo $? 2 not correctly executed.

Loop constructs - for and while :

17

Page 18: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

The for and while looping constructs allow a program to execute a command or sequence of

commands several times.

The for loop executes a sequence of commands once for each member of a list.

for variable in a_list_of_values do command_1 command_2 . . . last_command done.

The while loopAnother loop construct, the while loop, uses two groups of commands. It will continue executing

the sequence of commands in the second group, the do . . . done list, as long as the final

command in the first group, the while list, returns a status of (true), meaning the statements after

the do can be executed.

command_1 . . . last_command do command_1 . . . last_command done

Ex:$ cat enter.name while   read x do echo $x>>xfile done

18

Page 19: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

Conditional constructs: if and case

Conditional constructs cause branches in the path of execution based on the outcome of a comparison.

if . . . then

The if command tells the shell program to execute the then sequence of commands only if the

final command in the if command list is successful. The if construct ends with the keyword fi.

The general format for the if construct is given below.

if

command_1 . . . last_command then command_1 . . . last_command fi

Format of the if . . . then conditional construct

For example, a shell program called search demonstrates the use of the if . . . then construct.

The search program uses the grep command to search for a word in a file. If grep is successful,

the program echos that the word is found in the file.

$ cat search

echo Type in the word and the filename.

read word file

if grep $word $file

then echo $word is in $file

fi

19

Page 20: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

if . . . then . . . else construct.

The if . . . then construct can also issue an alternate set of commands with else, when the if

command sequence is false. when the if command sequence is false.

if command_1 . . . last_command then command_1 . . . last_command else command_1 . . . last_command fi

Unconditional control statements: break and continue

The break command unconditionally stops the execution of any loop in which it is encountered, and goes to the next command after the done, fi, or esac statement. If no commands follow that statement, the program ends.

In the example for set.term, ,the break commandis used instead of echo to leave the program,

$ cat set.term

echo If you have a TTY 4420 type in 4420

echo If you have a TTY 5410 type in 5410

echo If you have a TTY 5420 type in 5420

read term

case $term

20

Page 21: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

in

4420) TERM=T4 ;; 5410) TERM=T5 ;; 5420) TERM=T7 ;; *) break ;; esac export TERM echo end of program

The continue command causes the program to go immediately to the next iteration of a while or for loop without executing the remaining commands in the loop.

System Programming:

The system programming includes the usage of processes ,multi-threading ,semaphore and

Mutex usage shared memory and message queue usage for intertask-communication.

Processes: A process in Linux is defined as an instance of a running program.Each process is

associated with a unique Identification number known as PID. The value of PID will be between

2 and 32768.The process with PID of 1 is the is the ” init” process which manages all other

processes.

The idle process—the process that the kernel “runs” when there are no other runnable processes

—has the PID 0. The first process that the kernel executes after booting the system, called the

init process, has the PID 1. Normally, the init process on Linux is the init program. The term

“init” refers to both the initial process that the kernel runs, and the specific program used for that

purpose.

Each process has a stack space of its own in which local variables of the function and the return

values are stored.

To know the running processes at any time the shell command $ps -ef is used.

21

Page 22: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

To display the various processes with priority at any instant the shell command $ps -1 is used.

A new shell process can be created using the following C pogram.

# include <stdlib.h>

#include <stdio.h>

Int main() {

System(“ ls -1” ); // running a shell command with system function

Printf(“execution completed\n”);

Exit(0);

}

When this program is run ,a process is created and this in turn creates a new process to run the

command “ls -1”.

When a shell has to create a new process ,it calls a function fork( ).This function call returns a

new PID and the original process continues.

When the fork( ) cal returns 0 on success ,a new process is created.This new process runs

independent of the earlier process or parent process.

Multithreading:

Threads are units of execution within a single process. All processes have at least one thread.

Each thread has its own virtualization of the processor: its own set of registers, instruction

pointer, and processor state. Sometimes these processes may have large numbers of threads, all

performing different tasks, but sharing the same address space (and thus the same dynamic

memory, mapped files, object code, and so on), list of open files, and other kernel resources.

The Linux kernel has an interesting and unique view of threads. To the Linux kernel, all threads

are unique processes That is, the kernel considers a process consisting of two threads as two

distinct processes that share a set of kernel resources (address space, list of open files,and so on).

Multithreaded programming is the art of programming with threads. The most common API on

Linux for programming with threads is the API standardized by IEEE Std 1003.1c-1995 (POSIX

1995 or POSIX.1c). Developers often call this API pthreads.

Semaphores: In Linux ,the semaphore functions are included in the file <sys/semo.h> and hence

,one has to include th pre-processor directive #include<sys/sem.h> in the program that uses

semaphores.

22

Page 23: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

The out-put of the program with semaphores is different .Because ,without semaphore there will

be no co-ordination between the threads .i.e without the completion of the first thread

activity ,the second thread may be evoked. To avoid this ,the semaphores are used.The same

result can also be achieved by using Mutex function also. If ,semaphores are used ,the thread

converting the text will wait for a semaphore to be released before it starts the operation.

Shared memory: In system programming different threads or programs may have to use the

same memory.Let us assume that a memory of 1024 bytes is created. One program will read the

contents of the memory and another program will take input from a keyboard and write data to

this memory. The presence of data on the memory is denoted by a flag. So,the program that reads

the memory will clear the flag after reading and the program that puts the data on the memory

will set the flag after putting (writing) the data.

C/C++ programming on Linux

The C code used on Linux will be the same as that write on Windows/DOS, as long as

writing the ANSI C code. Some library functions, such as those provided by conio.h and

graphics.h, are not part of the ANSI standard. Hence, you won’t be able to use them on Linux.

The C compiler you use on Linux is GCC. It is part of the GNU Compiler Collection. Open a

terminal and run the command: gcc. If you see something like “no input files “ ,it means GCC

is already installed

$ gcc: no input files

However, if you see something like “Command not found”, then you will have to install GCC

using the package manager.

Besides a compiler, you also need the C standard library, called glibc, to compile the C

programs correctly. Type in locate glibc and check the output. If it shows directory structures of

the form /foo/bar/glibc or the like, then you glibc is installed ; else you need to install it.

After confirming the presence of a text editor, a compiler and the standard library, one can start

writing the code in C on Linux.

For the purpose , let’s create a sub-directory called ‘New’ under your ‘home’ directory, in which

all the source code is stored.

First type $ gedit . In the editor, type the C code .

Ex1: To find the factorial

#include<stdio.h>

23

Page 24: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

int main(int argc, char **argv)

{

int n, i, fact=1;

printf("Enter a number for which you want to find the factorial:: ");

scanf ("%d", &n);

for(i=1;i<=n;i++)

fact=fact*i;

printf("Factorial of %d is :: %dn", n,fact);

return (1);

}

Save this code in the sub-directory New with the name fact.c. Launch the shell program

(terminal), and run cd New to go to this directory. Now use the command at the terminal to

compile the program

$ gcc factorial.c

After executing the command, run ls and find a.out file in the current directory. This is the

executable file of the C program, compiled and linked with the appropriate libraries. To execute

it, run type $ ./a.out

Enter a number for which you want to find the factorial :: 5

Factorial of 5 is :: 120

Ex 2: To print Hello from Linux

#include <stdio.h>

int main(void)

{

printf("Hello from Linux\n");

return 0;

}

Save this code in the New sub-directory with the name hello.c Launch the shell program

(terminal), and run cd New to go to this directory. Type the following command:$ gcc hello.c

or gcc hello.c -o hello

24

Page 25: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

More about the a.out file : This is the Linux equivalent of the .exe file that is similar to

DOS/Windows; it is the executable form of the code. But , this file cannot be executed on DOS

or Windows, since it is in a different format.

Now, instead of renaming the executable file each time you compile, you can specify the output

file name to the compiler : $gcc -o factorial factorial.c

C++ program on Linux :

Let’s now write C++ program on Linux. The cycle of coding, compilation and execution is very

similar to that for C, except for the compiler we use, which is g++.

First ,check if it’s already installed by running the command at the terminal $g++. Next, using

the package manager check if libstdc++, the standard C++ library, is installed .(if not, install

it). Once both are installed, use the editor to type the C++ program.

Ex1: To print Hello World.

#include<iostream>

#include<string>

using namespace std;

int main(int argc, char **argv)

{

string s1="Hello";

string s2="World";

cout <<s1+" " + s2 << "n";

return 0;

}

Save this file as string-demo.cxx in the New subdirectory.

Compile and execute the file

:g++ -o string-demo string-demo.cpp ./string-demo

Running the above command should output the following on the terminal :Hello World

The C++ code you see is standard C++, with the .h omitted from the header files. C++ source

files conventionally use one of the suffixes .C, .cc, .cpp, .c++, .cp, or .cxx.

#include<iostream>

25

Page 26: UNIT II-Programming in Linux

Dr.Y.Narasimha Murthy.Ph.D [email protected]

using namespace std;

class Circle{

float r;

public:

void init(float x) /* Inline function */

{

r = x;

}

float area();

};

float Circle::area()

{

return 3.14*r*r;

}

int main(int argc, char **argv)

{

float radius;

Circle circle;

cout << "Enter the radius of the circle:: ";

cin >> radius;

circle.init(radius);

cout << "Area of the Circle:: "<<circle.area()<<"n";

return 0;

}

Save the file in the New sub-directory as class-demo.cxx.

Compile and execute it :g++ -o class-demo class-demo.cxx./class-demo

Enter the radius of the circle :: 4

Area of the Circle:: 50.24.

--------------------xxxxx-------------

References: 1.Embedded /Real time Systems – Dr.K.V.K.K.Prasad ,2002

2. Linux System Programming ,by Robert Love , O’Reilly Media, Inc.2007

26