SlideShare a Scribd company logo
1 of 26
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
1
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
2
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
3
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
4
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
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
5
 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
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
6
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
Editors:
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
7
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.
To search a file use the command find at the $ terminal.
Ex: $find
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
8
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.
So,here the output is redirected to a file instead of the monitor.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
9
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
10
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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
11
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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
12
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 CMD
5198 pts/1 00:00:00 bash
10129 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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
13
$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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
14
Name of the Shell Developer Developed at Remarks
BASH ( Bourne -
Again SHell )
Brian Fox
and Chet
Ramey
Free Software
Foundation
Most common shell in Linux.
It's Freeware shell.
CSH (C SHell) Bill Joy University of
California(For BSD)
The C shell's syntax and
usage 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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
15
6 LOGNAME=students Our logging name
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 = Bus
To define variable called n having value 10 we write $ n=10
Rules 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
HOME
SYSTEM_VERSION
veh
no.
(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=10
But 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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
16
$ 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) break
Comments :
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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
17
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 documents
A 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 :
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
18
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 loop
Another 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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
19
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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
20
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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
21
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
22
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 completedn”);
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.
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
23
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>
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
24
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 Linuxn");
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
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
25
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>
Dr.Y.Narasimha Murthy.Ph.D
yayavaram@yahoo.com
26
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

More Related Content

What's hot

Principles of operating system
Principles of operating systemPrinciples of operating system
Principles of operating systemAnil Dharmapuri
 
Kernel mode vs user mode in linux
Kernel mode vs user mode in linuxKernel mode vs user mode in linux
Kernel mode vs user mode in linuxSiddique Ibrahim
 
Windows Architecture Explained by Stacksol
Windows Architecture Explained by StacksolWindows Architecture Explained by Stacksol
Windows Architecture Explained by StacksolStacksol
 
Operating System BCA 301
Operating System BCA 301Operating System BCA 301
Operating System BCA 301cpjcollege
 
OPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTESOPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTESsuthi
 
Embedded os
Embedded osEmbedded os
Embedded oschian417
 
Operating systems system structures
Operating systems   system structuresOperating systems   system structures
Operating systems system structuresMukesh Chinta
 
Introduction to operating syatem
Introduction to operating syatemIntroduction to operating syatem
Introduction to operating syatemRafi Dar
 
Operating system notes
Operating system notesOperating system notes
Operating system notesSANTOSH RATH
 
COMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTESCOMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTESsuthi
 
Operating System a Case Study
Operating System a Case StudyOperating System a Case Study
Operating System a Case Studyijtsrd
 

What's hot (20)

02.Os Structure
02.Os Structure02.Os Structure
02.Os Structure
 
Cs8493 unit 5
Cs8493 unit 5Cs8493 unit 5
Cs8493 unit 5
 
CS6401 OPERATING SYSTEMS Unit 2
CS6401 OPERATING SYSTEMS Unit 2CS6401 OPERATING SYSTEMS Unit 2
CS6401 OPERATING SYSTEMS Unit 2
 
Principles of operating system
Principles of operating systemPrinciples of operating system
Principles of operating system
 
Kernel mode vs user mode in linux
Kernel mode vs user mode in linuxKernel mode vs user mode in linux
Kernel mode vs user mode in linux
 
operating system
operating systemoperating system
operating system
 
BASICS OF COMPUTER
BASICS OF COMPUTERBASICS OF COMPUTER
BASICS OF COMPUTER
 
Operatingsystem
OperatingsystemOperatingsystem
Operatingsystem
 
Windows Architecture Explained by Stacksol
Windows Architecture Explained by StacksolWindows Architecture Explained by Stacksol
Windows Architecture Explained by Stacksol
 
Operating System BCA 301
Operating System BCA 301Operating System BCA 301
Operating System BCA 301
 
CS6401 Operating Systems
CS6401 Operating SystemsCS6401 Operating Systems
CS6401 Operating Systems
 
OPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTESOPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTES
 
An Introduction to Operating Systems
An Introduction to Operating SystemsAn Introduction to Operating Systems
An Introduction to Operating Systems
 
Embedded os
Embedded osEmbedded os
Embedded os
 
Embedded operating systems
Embedded operating systemsEmbedded operating systems
Embedded operating systems
 
Operating systems system structures
Operating systems   system structuresOperating systems   system structures
Operating systems system structures
 
Introduction to operating syatem
Introduction to operating syatemIntroduction to operating syatem
Introduction to operating syatem
 
Operating system notes
Operating system notesOperating system notes
Operating system notes
 
COMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTESCOMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTES
 
Operating System a Case Study
Operating System a Case StudyOperating System a Case Study
Operating System a Case Study
 

Viewers also liked

UNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONS
UNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONSUNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONS
UNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONSDr.YNM
 
UNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONS
UNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONSUNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONS
UNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONSDr.YNM
 
RTOS APPLICATIONS
RTOS  APPLICATIONSRTOS  APPLICATIONS
RTOS APPLICATIONSDr.YNM
 
UNIT-IV .FINITE STATE MACHINES
UNIT-IV .FINITE STATE MACHINESUNIT-IV .FINITE STATE MACHINES
UNIT-IV .FINITE STATE MACHINESDr.YNM
 
Vlsi physical design-notes
Vlsi physical design-notesVlsi physical design-notes
Vlsi physical design-notesDr.YNM
 
UNIT-II : SEQUENTIAL CIRCUIT DESIGN
UNIT-II  : SEQUENTIAL CIRCUIT DESIGN UNIT-II  : SEQUENTIAL CIRCUIT DESIGN
UNIT-II : SEQUENTIAL CIRCUIT DESIGN Dr.YNM
 
UNIT-II -DIGITAL SYSTEM DESIGN
UNIT-II -DIGITAL SYSTEM DESIGNUNIT-II -DIGITAL SYSTEM DESIGN
UNIT-II -DIGITAL SYSTEM DESIGNDr.YNM
 
UNIT-III-DIGITAL SYSTEM DESIGN
UNIT-III-DIGITAL SYSTEM DESIGNUNIT-III-DIGITAL SYSTEM DESIGN
UNIT-III-DIGITAL SYSTEM DESIGNDr.YNM
 
Arm processors' architecture
Arm processors'   architectureArm processors'   architecture
Arm processors' architectureDr.YNM
 
UNIT-I DIGITAL SYSTEM DESIGN
UNIT-I DIGITAL SYSTEM DESIGN UNIT-I DIGITAL SYSTEM DESIGN
UNIT-I DIGITAL SYSTEM DESIGN Dr.YNM
 
UNIT-I-RTOS and Concepts
UNIT-I-RTOS and ConceptsUNIT-I-RTOS and Concepts
UNIT-I-RTOS and ConceptsDr.YNM
 
Verilog hdl design examples
Verilog hdl design examplesVerilog hdl design examples
Verilog hdl design examplesdennis gookyi
 
faults in digital systems
faults in digital systemsfaults in digital systems
faults in digital systemsdennis gookyi
 
PLA Minimization -Testing
PLA Minimization -TestingPLA Minimization -Testing
PLA Minimization -TestingDr.YNM
 
Vlsi design notes(1st unit) according to vtu syllabus.(BE)
Vlsi  design notes(1st unit) according to vtu syllabus.(BE)Vlsi  design notes(1st unit) according to vtu syllabus.(BE)
Vlsi design notes(1st unit) according to vtu syllabus.(BE)instrumentation_vtu
 
UNIT-II CPLD & FPGA Architectures and Applications
UNIT-II CPLD & FPGA  Architectures   and ApplicationsUNIT-II CPLD & FPGA  Architectures   and Applications
UNIT-II CPLD & FPGA Architectures and ApplicationsDr.YNM
 
Introduction to image processing-Class Notes
Introduction to image processing-Class NotesIntroduction to image processing-Class Notes
Introduction to image processing-Class NotesDr.YNM
 
Semi Custom Integrated Circuit Design
 Semi Custom Integrated Circuit Design Semi Custom Integrated Circuit Design
Semi Custom Integrated Circuit DesignDr.YNM
 
Introduction to VLSI Technology
Introduction to VLSI TechnologyIntroduction to VLSI Technology
Introduction to VLSI TechnologyDr.YNM
 

Viewers also liked (20)

UNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONS
UNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONSUNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONS
UNIT I- CPLD & FPGA ARCHITECTURE & APPLICATIONS
 
UNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONS
UNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONSUNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONS
UNIT-V-FPGA &CPLD ARCHITECTURES AND APPLICATIONS
 
RTOS APPLICATIONS
RTOS  APPLICATIONSRTOS  APPLICATIONS
RTOS APPLICATIONS
 
UNIT-IV .FINITE STATE MACHINES
UNIT-IV .FINITE STATE MACHINESUNIT-IV .FINITE STATE MACHINES
UNIT-IV .FINITE STATE MACHINES
 
Vlsi physical design-notes
Vlsi physical design-notesVlsi physical design-notes
Vlsi physical design-notes
 
UNIT-II : SEQUENTIAL CIRCUIT DESIGN
UNIT-II  : SEQUENTIAL CIRCUIT DESIGN UNIT-II  : SEQUENTIAL CIRCUIT DESIGN
UNIT-II : SEQUENTIAL CIRCUIT DESIGN
 
UNIT-II -DIGITAL SYSTEM DESIGN
UNIT-II -DIGITAL SYSTEM DESIGNUNIT-II -DIGITAL SYSTEM DESIGN
UNIT-II -DIGITAL SYSTEM DESIGN
 
UNIT-III-DIGITAL SYSTEM DESIGN
UNIT-III-DIGITAL SYSTEM DESIGNUNIT-III-DIGITAL SYSTEM DESIGN
UNIT-III-DIGITAL SYSTEM DESIGN
 
Arm processors' architecture
Arm processors'   architectureArm processors'   architecture
Arm processors' architecture
 
UNIT-I DIGITAL SYSTEM DESIGN
UNIT-I DIGITAL SYSTEM DESIGN UNIT-I DIGITAL SYSTEM DESIGN
UNIT-I DIGITAL SYSTEM DESIGN
 
UNIT-I-RTOS and Concepts
UNIT-I-RTOS and ConceptsUNIT-I-RTOS and Concepts
UNIT-I-RTOS and Concepts
 
test generation
test generationtest generation
test generation
 
Verilog hdl design examples
Verilog hdl design examplesVerilog hdl design examples
Verilog hdl design examples
 
faults in digital systems
faults in digital systemsfaults in digital systems
faults in digital systems
 
PLA Minimization -Testing
PLA Minimization -TestingPLA Minimization -Testing
PLA Minimization -Testing
 
Vlsi design notes(1st unit) according to vtu syllabus.(BE)
Vlsi  design notes(1st unit) according to vtu syllabus.(BE)Vlsi  design notes(1st unit) according to vtu syllabus.(BE)
Vlsi design notes(1st unit) according to vtu syllabus.(BE)
 
UNIT-II CPLD & FPGA Architectures and Applications
UNIT-II CPLD & FPGA  Architectures   and ApplicationsUNIT-II CPLD & FPGA  Architectures   and Applications
UNIT-II CPLD & FPGA Architectures and Applications
 
Introduction to image processing-Class Notes
Introduction to image processing-Class NotesIntroduction to image processing-Class Notes
Introduction to image processing-Class Notes
 
Semi Custom Integrated Circuit Design
 Semi Custom Integrated Circuit Design Semi Custom Integrated Circuit Design
Semi Custom Integrated Circuit Design
 
Introduction to VLSI Technology
Introduction to VLSI TechnologyIntroduction to VLSI Technology
Introduction to VLSI Technology
 

Similar to UNIT II-Programming in Linux

Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya JyothiIntroduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya JyothiSowmya Jyothi
 
Unix Operating System
Unix Operating SystemUnix Operating System
Unix Operating Systemsubhsikha
 
LinuxOS-1 (1).ppt
LinuxOS-1 (1).pptLinuxOS-1 (1).ppt
LinuxOS-1 (1).pptSavitha74
 
Unix operating system architecture with file structure
Unix operating system architecture with file structure Unix operating system architecture with file structure
Unix operating system architecture with file structure amol_chavan
 
Introduction to Unix Concets.pptx
Introduction to Unix Concets.pptxIntroduction to Unix Concets.pptx
Introduction to Unix Concets.pptxHarsha Patel
 
Introduction to Unix Concets.pptx
Introduction to Unix Concets.pptxIntroduction to Unix Concets.pptx
Introduction to Unix Concets.pptxHarsha Patel
 
CHAPTER 1 INTRODUCTION TO UNIX.pptx
CHAPTER 1 INTRODUCTION TO UNIX.pptxCHAPTER 1 INTRODUCTION TO UNIX.pptx
CHAPTER 1 INTRODUCTION TO UNIX.pptxMahiDivya
 
Introduction to unix (1).pptx
Introduction to unix (1).pptxIntroduction to unix (1).pptx
Introduction to unix (1).pptxvirat834293
 
84640411 study-of-unix-os
84640411 study-of-unix-os84640411 study-of-unix-os
84640411 study-of-unix-oshomeworkping3
 
Linux and Java - Understanding and Troubleshooting
Linux and Java - Understanding and TroubleshootingLinux and Java - Understanding and Troubleshooting
Linux and Java - Understanding and TroubleshootingJérôme Kehrli
 
16. Computer Systems Basic Software 2
16. Computer Systems   Basic Software 216. Computer Systems   Basic Software 2
16. Computer Systems Basic Software 2New Era University
 
UNIT I LINUX.docx
UNIT I LINUX.docxUNIT I LINUX.docx
UNIT I LINUX.docxBhuvanaR13
 

Similar to UNIT II-Programming in Linux (20)

Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya JyothiIntroduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
 
Unix Operating System
Unix Operating SystemUnix Operating System
Unix Operating System
 
LinuxOS-1 (1).ppt
LinuxOS-1 (1).pptLinuxOS-1 (1).ppt
LinuxOS-1 (1).ppt
 
Unix operating system architecture with file structure
Unix operating system architecture with file structure Unix operating system architecture with file structure
Unix operating system architecture with file structure
 
Unix case-study
Unix case-studyUnix case-study
Unix case-study
 
Introduction to unix
Introduction to unixIntroduction to unix
Introduction to unix
 
3CS LSP UNIT 1-1.pdf
3CS LSP UNIT 1-1.pdf3CS LSP UNIT 1-1.pdf
3CS LSP UNIT 1-1.pdf
 
UNIX_module1.pptx
UNIX_module1.pptxUNIX_module1.pptx
UNIX_module1.pptx
 
Introduction to Unix Concets.pptx
Introduction to Unix Concets.pptxIntroduction to Unix Concets.pptx
Introduction to Unix Concets.pptx
 
Introduction to Unix Concets.pptx
Introduction to Unix Concets.pptxIntroduction to Unix Concets.pptx
Introduction to Unix Concets.pptx
 
CHAPTER 1 INTRODUCTION TO UNIX.pptx
CHAPTER 1 INTRODUCTION TO UNIX.pptxCHAPTER 1 INTRODUCTION TO UNIX.pptx
CHAPTER 1 INTRODUCTION TO UNIX.pptx
 
Introduction to unix (1).pptx
Introduction to unix (1).pptxIntroduction to unix (1).pptx
Introduction to unix (1).pptx
 
UNIX_Module 1.pdf
UNIX_Module 1.pdfUNIX_Module 1.pdf
UNIX_Module 1.pdf
 
Spsl unit1
Spsl   unit1Spsl   unit1
Spsl unit1
 
84640411 study-of-unix-os
84640411 study-of-unix-os84640411 study-of-unix-os
84640411 study-of-unix-os
 
Linux and Java - Understanding and Troubleshooting
Linux and Java - Understanding and TroubleshootingLinux and Java - Understanding and Troubleshooting
Linux and Java - Understanding and Troubleshooting
 
16. Computer Systems Basic Software 2
16. Computer Systems   Basic Software 216. Computer Systems   Basic Software 2
16. Computer Systems Basic Software 2
 
UNIT I LINUX.docx
UNIT I LINUX.docxUNIT I LINUX.docx
UNIT I LINUX.docx
 
Presentation1.pdf
Presentation1.pdfPresentation1.pdf
Presentation1.pdf
 

More from Dr.YNM

Introduction to DSP.ppt
Introduction to DSP.pptIntroduction to DSP.ppt
Introduction to DSP.pptDr.YNM
 
Atmel.ppt
Atmel.pptAtmel.ppt
Atmel.pptDr.YNM
 
PIC Microcontrollers.ppt
PIC Microcontrollers.pptPIC Microcontrollers.ppt
PIC Microcontrollers.pptDr.YNM
 
Crystalstructure-.ppt
Crystalstructure-.pptCrystalstructure-.ppt
Crystalstructure-.pptDr.YNM
 
Basics of OS & RTOS.ppt
Basics of OS & RTOS.pptBasics of OS & RTOS.ppt
Basics of OS & RTOS.pptDr.YNM
 
Introducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptxIntroducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptxDr.YNM
 
Microcontroller-8051.ppt
Microcontroller-8051.pptMicrocontroller-8051.ppt
Microcontroller-8051.pptDr.YNM
 
Introduction to ASICs.pptx
Introduction to ASICs.pptxIntroduction to ASICs.pptx
Introduction to ASICs.pptxDr.YNM
 
VHDL-PRESENTATION.ppt
VHDL-PRESENTATION.pptVHDL-PRESENTATION.ppt
VHDL-PRESENTATION.pptDr.YNM
 
Basics of data communications.pptx
Basics of data communications.pptxBasics of data communications.pptx
Basics of data communications.pptxDr.YNM
 
CPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptxCPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptxDr.YNM
 
Transient response of RC , RL circuits with step input
Transient response of RC , RL circuits  with step inputTransient response of RC , RL circuits  with step input
Transient response of RC , RL circuits with step inputDr.YNM
 
CISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURESCISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURESDr.YNM
 
Lect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTURELect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTUREDr.YNM
 
Lect 3 ARM PROCESSOR ARCHITECTURE
Lect 3  ARM PROCESSOR ARCHITECTURE Lect 3  ARM PROCESSOR ARCHITECTURE
Lect 3 ARM PROCESSOR ARCHITECTURE Dr.YNM
 
Microprocessor Architecture 4
Microprocessor Architecture  4Microprocessor Architecture  4
Microprocessor Architecture 4Dr.YNM
 
Lect 2 ARM processor architecture
Lect 2 ARM processor architectureLect 2 ARM processor architecture
Lect 2 ARM processor architectureDr.YNM
 
Microprocessor Architecture-III
Microprocessor Architecture-IIIMicroprocessor Architecture-III
Microprocessor Architecture-IIIDr.YNM
 
LECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORSLECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORSDr.YNM
 
Microprocessor architecture II
Microprocessor architecture   IIMicroprocessor architecture   II
Microprocessor architecture IIDr.YNM
 

More from Dr.YNM (20)

Introduction to DSP.ppt
Introduction to DSP.pptIntroduction to DSP.ppt
Introduction to DSP.ppt
 
Atmel.ppt
Atmel.pptAtmel.ppt
Atmel.ppt
 
PIC Microcontrollers.ppt
PIC Microcontrollers.pptPIC Microcontrollers.ppt
PIC Microcontrollers.ppt
 
Crystalstructure-.ppt
Crystalstructure-.pptCrystalstructure-.ppt
Crystalstructure-.ppt
 
Basics of OS & RTOS.ppt
Basics of OS & RTOS.pptBasics of OS & RTOS.ppt
Basics of OS & RTOS.ppt
 
Introducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptxIntroducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptx
 
Microcontroller-8051.ppt
Microcontroller-8051.pptMicrocontroller-8051.ppt
Microcontroller-8051.ppt
 
Introduction to ASICs.pptx
Introduction to ASICs.pptxIntroduction to ASICs.pptx
Introduction to ASICs.pptx
 
VHDL-PRESENTATION.ppt
VHDL-PRESENTATION.pptVHDL-PRESENTATION.ppt
VHDL-PRESENTATION.ppt
 
Basics of data communications.pptx
Basics of data communications.pptxBasics of data communications.pptx
Basics of data communications.pptx
 
CPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptxCPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptx
 
Transient response of RC , RL circuits with step input
Transient response of RC , RL circuits  with step inputTransient response of RC , RL circuits  with step input
Transient response of RC , RL circuits with step input
 
CISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURESCISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURES
 
Lect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTURELect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTURE
 
Lect 3 ARM PROCESSOR ARCHITECTURE
Lect 3  ARM PROCESSOR ARCHITECTURE Lect 3  ARM PROCESSOR ARCHITECTURE
Lect 3 ARM PROCESSOR ARCHITECTURE
 
Microprocessor Architecture 4
Microprocessor Architecture  4Microprocessor Architecture  4
Microprocessor Architecture 4
 
Lect 2 ARM processor architecture
Lect 2 ARM processor architectureLect 2 ARM processor architecture
Lect 2 ARM processor architecture
 
Microprocessor Architecture-III
Microprocessor Architecture-IIIMicroprocessor Architecture-III
Microprocessor Architecture-III
 
LECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORSLECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORS
 
Microprocessor architecture II
Microprocessor architecture   IIMicroprocessor architecture   II
Microprocessor architecture II
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

UNIT II-Programming in Linux

  • 1. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 1 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.
  • 2. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 2 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.
  • 3. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 3 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.
  • 4. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 4 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 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.
  • 5. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 5  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 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.
  • 6. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 6 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 Editors:
  • 7. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 7 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. To search a file use the command find at the $ terminal. Ex: $find
  • 8. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 8 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. So,here the output is redirected to a file instead of the monitor.
  • 9. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 9 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.
  • 10. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 10 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
  • 11. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 11 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
  • 12. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 12 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 CMD 5198 pts/1 00:00:00 bash 10129 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.
  • 13. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 13 $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.
  • 14. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 14 Name of the Shell Developer Developed at Remarks BASH ( Bourne - Again SHell ) Brian Fox and Chet Ramey Free Software Foundation Most common shell in Linux. It's Freeware shell. CSH (C SHell) Bill Joy University of California(For BSD) The C shell's syntax and usage 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
  • 15. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 15 6 LOGNAME=students Our logging name 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 = Bus To define variable called n having value 10 we write $ n=10 Rules 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 HOME SYSTEM_VERSION veh no. (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=10 But 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
  • 16. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 16 $ 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) break Comments : 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
  • 17. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 17 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 documents A 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 :
  • 18. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 18 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 loop Another 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
  • 19. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 19 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
  • 20. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 20 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
  • 21. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 21 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.
  • 22. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 22 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 completedn”); 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.
  • 23. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 23 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>
  • 24. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 24 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 Linuxn"); 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
  • 25. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 25 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>
  • 26. Dr.Y.Narasimha Murthy.Ph.D yayavaram@yahoo.com 26 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