Linux Programming
Linux Programming
in JNTU World
Linux Programming
Linux is a Unix-like computer operating system assembled under the model of free and open
source software development and distribution. The defining component of Linux is the Linux
ld
kernel, an operating system kernel first released 5 October 1991 by Linus Torvalds.
Linux was originally developed as a free operating system for Intel x86-based personal
computers. It has since been ported to more computer hardware platforms than any other
or
operating system. It is a leading operating system on servers and other big iron systems such as
mainframe computers and supercomputers more than 90% of today's 500 fastest supercomputers
run some variant of Linux, including the 10 fastest. Linux also runs on embedded systems
W
(devices where the operating system is typically built into the firmware and highly tailored to the
system) such as mobile phones, tablet computers, network routers, televisions and video game
consoles; the Android system in wide use on mobile devices is built on the Linux kernel.
A distribution oriented toward desktop use will typically include the X Window System and an
accompanying desktop environment such as GNOME or KDE Plasma. Some such distributions
TU
may include a less resource intensive desktop such as LXDE or Xfce for use on older or less
powerful computers. A distribution intended to run as a server may omit all graphical
environments from the standard install and instead include other software such as the Apache
HTTP Server and an SSH server such as OpenSSH. Because Linux is freely redistributable,
anyone may create a distribution for any intended use. Applications commonly used with
desktop Linux systems include the Mozilla Firefox web browser, the LibreOffice office
application suite, and the GIMP image editor.
JN
Since the main supporting user space system tools and libraries originated in the GNU Project,
initiated in 1983 by Richard Stallman, the Free Software Foundation prefers the name
GNU/Linux.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
History
Unix
The Unix operating system was conceived and implemented in 1969 at AT&T's Bell
Laboratories in the United States by Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe
ld
Ossanna. It was first released in 1971 and was initially entirely written in assembly language, a
common practice at the time. Later, in a key pioneering approach in 1973, Unix was re-written in
the programming language C by Dennis Ritchie (with exceptions to the kernel and I/O). The
availability of an operating system written in a high-level language allowed easier portability to
or
different computer platforms.
Today, Linux systems are used in every domain, from embedded systems to supercomputers, and
have secured a place in server installations often using the popular LAMP application stack. Use
W
of Linux distributions in home and enterprise desktops has been growing. They have also gained
popularity with various local and national governments. The federal government of Brazil is well
known for its support for Linux. News of the Russian military creating its own Linux distribution
has also surfaced, and has come to fruition as the G.H.ost Project. The Indian state of Kerala has
gone to the extent of mandating that all state high schools run Linux on their computers.
TU
Design
A Linux-based system is a modular Unix-like operating system. It derives much of its basic
design from principles established in Unix during the 1970s and 1980s. Such a system uses a
monolithic kernel, the Linux kernel, which handles process control, networking, and peripheral
and file system access. Device drivers are either integrated directly with the kernel or added as
JN
Separate projects that interface with the kernel provide much of the system's higher-level
functionality. The GNU userland is an important part of most Linux-based systems, providing
the most common implementation of the C library, a popular shell, and many of the common
Unix tools which carry out many basic operating system tasks. The graphical user interface (or
GUI) used by most Linux systems is built on top of an implementation of the X Window System.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Programming on Linux
Most Linux distributions support dozens of programming languages. The original development
tools used for building both Linux applications and operating system programs are found within
the GNU toolchain, which includes the GNU Compiler Collection (GCC) and the GNU build
system. Amongst others, GCC provides compilers for Ada, C, C++, Java, and Fortran. First
ld
released in 2003, the Low Level Virtual Machine project provides an alternative open-source
compiler for many languages. Proprietary compilers for Linux include the Intel C++ Compiler,
Sun Studio, and IBM XL C/C++ Compiler. BASIC in the form of Visual Basic is supported in
or
such forms as Gambas, FreeBASIC, and XBasic.
Most distributions also include support for PHP, Perl, Ruby, Python and other dynamic
languages. While not as common, Linux also supports C# (via Mono), Vala, and Scheme. A
W
number of Java Virtual Machines and development kits run on Linux, including the original Sun
Microsystems JVM (HotSpot), and IBM's J2SE RE, as well as many open-source projects like
Kaffe and JikesRVM.
Linux Advantages
1. Low cost: You don’t need to spend time and money to obtain licenses since Linux and
TU
much of its software come with the GNU General Public License. You can start to work
immediately without worrying that your software may stop working anytime because the
free trial version expires. Additionally, there are large repositories from which you can
freely download high quality software for almost any task you can think of.
2. Stability: Linux doesn’t need to be rebooted periodically to maintain performance levels. It
doesn’t freeze up or slow down over time due to memory leaks and such. Continuous up-
times of hundreds of days (up to a year or more) are not uncommon.
3. Performance: Linux provides persistent high performance on workstations and on
JN
networks. It can handle unusually large numbers of users simultaneously, and can make old
computers sufficiently responsive to be useful again.
4. Network friendliness: Linux was developed by a group of programmers over the Internet
and has therefore strong support for network functionality; client and server systems can be
easily set up on any computer running Linux. It can perform tasks such as network backups
faster and more reliably than alternative systems.
5. Flexibility: Linux can be used for high performance server applications, desktop
applications, and embedded systems. You can save disk space by only installing the
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
components needed for a particular use. You can restrict the use of specific computers by
installing for example only selected office applications instead of the whole suite.
6. Compatibility: It runs all common Unix software packages and can process all common
file formats.
7. Choice: The large number of Linux distributions gives you a choice. Each distribution is
developed and supported by a different organization. You can pick the one you like best;
the core functionalities are the same; most software runs on most distributions.
ld
8. Fast and easy installation: Most Linux distributions come with user-friendly installation
and setup programs. Popular Linux distributions come with tools that make installation of
additional software very user friendly as well.
9. Full use of hard disk: Linux continues work well even when the hard disk is almost full.
10. Multitasking: Linux is designed to do many things at the same time; e.g., a large printing
or
job in the background won’t slow down your other work.
11. Security: Linux is one of the most secure operating systems. “Walls” and flexible file
access permission systems prevent access by unwanted visitors or viruses. Linux users have
to option to select and safely download software, free of charge, from online repositories
containing thousands of high quality packages. No purchase transactions requiring credit
W
card numbers or other sensitive personal information are necessary.
12. Open Source: If you develop software that requires knowledge or modification of the
operating system code, Linux’s source code is at your fingertips. Most Linux applications
are Open Source as well.
UNIX is copyrighted name only big companies are allowed to use the UNIX copyright and
TU
name, so IBM AIX and Sun Solaris and HP-UX all are UNIX operating systems. The Open
Group holds the UNIX trademark in trust for the industry, and manages the UNIX trademark
licensing program.
But if you consider Portable Operating System Interface (POSIX) standards then Linux can be
considered as UNIX. To quote from Official Linux kernel README file:
Linux is a Unix clone written from scratch by Linus Torvalds with assistance from a loosely-knit
team of hackers across the Net. It aims towards POSIX compliance.
However, "Open Group" do not approve of the construction "Unix-like", and consider it misuse
of their UNIX trademark.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
As I said earlier Linux is just a kernel and Linux distribution makes it complete usable operating
systems by adding various applications. Most UNIX operating systems comes with A-Z
programs such as editor, compilers etc. For example HP-UX or Solaris comes with A-Z
or
programs.
User-Friendly
Linux is considered as most user friendly UNIX like operating systems. It makes it easy to install
TU
sound card, flash players, and other desktop goodies. However, Apple OS X is most popular
UNIX operating system for desktop usage.
File Systems
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
2. Suse Linux comes with Yast
3. Redhat Linux comes with its own gui tools called redhat-config-*.
However, editing text config file and typing commands are most popular options for sys admin
work under UNIX and Linux.
or
System Startup Scripts
Almost every version of UNIX and Linux comes with system initialization script but they are
located in different directories:
1. HP-UX - /sbin/init.d
2. AIX - /etc/rc.d/init.d
3. Linux - /etc/init.d
W
End User Perspective
The differences are not that big for the average end user. They will use the same shell (e.g. bash
TU
or ksh) and other development tools such as Perl or Eclipse development tool.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
1. HP-UX
2. IBM AIX
3. Sun Solairs
ld
4. Mac OS X
5. IRIX
or
A few popular names:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
You can look at this from both sides of the fence. Some say giving the public access to the code
opens the operating system (and the software that runs on top of it) to malicious developers who
will take advantage of any weakness they find. Others say that having full access to the code
helps bring about faster improvements and bug fixes to keep those malicious developers from
being able to bring the system down. I have, on occasion, dipped into the code of one Linux
application or another, and when all was said and done, was happy with the results. Could I have
done that with a closed-source Windows application? No.
ld
#2: Licensing freedom vs. licensing restrictions
Along with access comes the difference between the licenses. I’m sure that every IT professional
could go on and on about licensing of PC software. But let’s just look at the key aspect of the
or
licenses (without getting into legalese). With a Linux GPL-licensed operating system, you are
free to modify that software and use and even republish or sell it (so long as you make the code
available). Also, with the GPL, you can download a single copy of a Linux distribution (or
application) and install it on as many machines as you like. With the Microsoft license, you can
do none of the above. You are bound to the number of licenses you purchase, so if you purchase
W
10 licenses, you can legally install that operating system (or application) on only 10 machines.
However, when you use the peer support inherent in Linux, you do fall prey to time. You could
have an issue with something, send out e-mail to a mailing list or post on a forum, and within 10
minutes be flooded with suggestions. Or these suggestions could take hours of days to come in. It
seems all up to chance sometimes. Still, generally speaking, most problems with Linux have
been encountered and documented. So chances are good you’ll find your solution fairly quickly.
On the other side of the coin is support for Windows. Yes, you can go the same route with
Microsoft and depend upon your peers for solutions. There are just as many help
JN
sites/lists/forums for Windows as there are for Linux. And you can purchase support from
Microsoft itself. Most corporate higher-ups easily fall victim to the safety net that having a
support contract brings. But most higher-ups haven’t had to depend up on said support contract.
Of the various people I know who have used either a Linux paid support contract or a Microsoft
paid support contract, I can’t say one was more pleased than the other. This of course begs the
question “Why do so many say that Microsoft support is superior to Linux paid support?”
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
One issue that is slowly becoming nonexistent is hardware support. Years ago, if you wanted to
install Linux on a machine you had to make sure you hand-picked each piece of hardware or
your installation would not work 100 percent. I can remember, back in 1997-ish, trying to figure
out why I couldn’t get Caldera Linux or Red Hat Linux to see my modem. After much looking
around, I found I was the proud owner of a Winmodem. So I had to go out and purchase a US
Robotics external modem because that was the one modem I knew would work. This is not so
much the case now. You can grab a PC (or laptop) and most likely get one or more Linux
ld
distributions to install and work nearly 100 percent. But there are still some exceptions. For
instance, hibernate/suspend remains a problem with many laptops, although it has come a long
way.
With Windows, you know that most every piece of hardware will work with the operating
or
system. Of course, there are times (and I have experienced this over and over) when you will
wind up spending much of the day searching for the correct drivers for that piece of hardware
you no longer have the install disk for. But you can go out and buy that 10-cent Ethernet card
and know it’ll work on your machine (so long as you have, or can find, the drivers). You also can
rest assured that when you purchase that insanely powerful graphics card, you will probably be
able to take full advantage of its power.
W
#5: Command line vs. no command line
No matter how far the Linux operating system has come and how amazing the desktop
environment becomes, the command line will always be an invaluable tool for administration
purposes. Nothing will ever replace my favorite text-based editor, ssh, and any given command-
line tool. I can’t imagine administering a Linux machine without the command line. But for the
end user — not so much. You could use a Linux machine for years and never touch the
TU
command line. Same with Windows. You can still use the command line with Windows, but not
nearly to the extent as with Linux. And Microsoft tends to obfuscate the command prompt from
users. Without going to Run and entering cmd (or command, or whichever it is these days), the
user won’t even know the command-line tool exists. And if a user does get the Windows
command line up and running, how useful is it really?
second. With Linux you have (with nearly every distribution) a centralized location where you
can search for, add, or remove software. I’m talking about package management systems, such as
Synaptic. With Synaptic, you can open up one tool, search for an application (or group of
applications), and install that application without having to do any Web searching (or
purchasing).
Windows has nothing like this. With Windows, you must know where to find the software you
want to install, download the software (or put the CD into your machine), and run setup.exe or
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
install.exe with a simple double-click. For many years, it was thought that installing applications
on Windows was far easier than on Linux. And for many years, that thought was right on target.
Not so much now. Installation under Linux is simple, painless, and centralized.
ld
ceiling are either movable or not. With Linux, you have a room where the floor and ceiling can
be raised or lowered, at will, as high or low as you want to make them. With Windows, that floor
and ceiling are immovable. You can’t go further than Microsoft has deemed it necessary to go.
Take, for instance, the desktop. Unless you are willing to pay for and install a third-party
or
application that can alter the desktop appearance, with Windows you are stuck with what
Microsoft has declared is the ideal desktop for you. With Linux, you can pretty much make your
desktop look and feel exactly how you want/need. You can have as much or as little on your
desktop as you want. From simple flat Fluxbox to a full-blown 3D Compiz experience, the Linux
desktop is as flexible an environment as there is on a computer.
Linux, it has to make do without the help of the marketing budgets and deep pockets of
Microsoft. With that comes the need for fans to help spread the word. And word of mouth is the
best friend of Linux.
Some see the fanaticism as the same college-level hoorah that keeps Linux in the basements for
LUG meetings and science projects. But I beg to differ. Another company, thanks to the
phenomenon of a simple music player and phone, has fallen into the same fanboy fanaticism, and
yet that company’s image has not been besmirched because of that fanaticism. Windows does
JN
not have these same fans. Instead, Windows has a league of paper-certified administrators who
believe the hype when they hear the misrepresented market share numbers reassuring them they
will be employable until the end of time.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
drive to access the contents of a CD is completely foreign to new users. There is a reason this is
the way it is. Because Linux has always been a multiuser platform, it was thought that forcing a
user to mount a media to use it would keep the user’s files from being overwritten by another
user. Think about it: On a multiuser system, if everyone had instant access to a disk that had been
inserted, what would stop them from deleting or overwriting a file you had just added to the
media? Things have now evolved to the point where Linux subsystems are set up so that you can
use a removable device in the same way you use them in Windows. But it’s not the norm. And
ld
besides, who doesn’t want to manually edit the /etc/fstab fle?
#10: Multilayered run levels vs. a single-layered run level
I couldn’t figure out how best to title this point, so I went with a description. What I’m talking
about is Linux’ inherent ability to stop at different run levels. With this, you can work from
or
either the command line (run level 3) or the GUI (run level 5). This can really save your socks
when X Windows is fubared and you need to figure out the problem. You can do this by booting
into run level 3, logging in as root, and finding/fixing the problem.
With Windows, you’re lucky to get to a command line via safe mode — and then you may or
W
may not have the tools you need to fix the problem. In Linux, even in run level 3, you can still
get and install a tool to help you out (hello apt-get install APPLICATION via the command line).
Having different run levels is helpful in another way. Say the machine in question is a Web or
mail server. You want to give it all the memory you have, so you don’t want the machine to boot
into run level 5. However, there are times when you do want the GUI for administrative purposes
(even though you can fully administer a Linux server from the command line). Because you can
run the startxcommand from the command line at run level 3, you can still start up X Windows
and have your GUI as well. With Windows, you are stuck at the Graphical run level unless you
TU
cat COMMAND:
cat linux command concatenates files and print it on the standard output.
JN
SYNTAX:
The Syntax is
cat [OPTIONS] [FILE]...
OPTIONS:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
ld
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
Non-printing characters (with the exception of tabs, new-lines and form-feeds)
-v
or
are printed visibly.
EXAMPLE:
To append data into the same file use append operator >> to write into the file, else the
file will be overwritten (i.e., all of its contents will be erased).
JN
3. To display a file:
cat file1.txt
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The above cat command will concatenate the two files (file1.txt and file2.txt) and it will
display the output in the screen. Some times the output may not fit the monitor screen. In
such situation you can print those files in a new file or display the file using less
command.
ld
cat file1.txt file2.txt | less
or
cat file1.txt file2.txt > file3.txt
In the above example the output is redirected to new file file3.txt. The cat command will
rm COMMAND:
W
create new file file3.txt and store the concatenated output into file3.txt.
SYNTAX:
TU
The Syntax is
rm [options..] [file | directory]
OPTIONS:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
EXAMPLE:
rm file1.txt
ld
Here rm command will remove/delete the file file1.txt.
or
rm -ir tmp
This rm command recursively removes the contents of all subdirectories of the tmp
directory, prompting you regarding the removal of each file, and then removes the tmp
directory itself.
W
3. To remove more files at once
rm file1.txt file2.txt
TU
rm command removes file1.txt and file2.txt files at the same time.
cd COMMAND:
cd command is used to change the directory.
SYNTAX:
The Syntax is
JN
cd [directory | ~ | ./ | ../ | - ]
OPTIONS:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
EXAMPLE:
1. cd linux-command
This command will take you to the sub-directory(linux-command) from its parent
ld
directory.
2. cd ..
or
This will change to the parent-directory from the current working directory/sub-directory.
3. cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
W
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into the
directory (the directory is not overwritten).
TU
SYNTAX:
The Syntax is
cp [OPTIONS]... SOURCE DEST
cp [OPTIONS]... SOURCE... DIRECTORY
cp [OPTIONS]... --target-directory=DIRECTORY SOURCE...
JN
OPTIONS:
-a same as -dpR.
--backup[=CONTROL] make a backup of each existing destination file
-b like --backup but does not accept an argument.
-f if an existing destination file cannot be opened, remove it and try
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
again.
-p same as --preserve=mode,ownership,timestamps.
preserve the specified attributes (default:
--
mode,ownership,timestamps) and security contexts, if possible
preserve[=ATTR_LIST]
additional attributes: links, all.
ld
--no-
don't preserve the specified attribute.
preserve=ATTR_LIST
--parents append source path to DIRECTORY.
EXAMPLE:
or
1. Copy two files:
cp file1 file2 W
The above cp command copies the content of file1.php to file2.php.
cp -b file1.php file2.php
cp -R scripts scripts1
The above cp command copy the folder and subfolders from scripts to scripts1.
ls COMMAND:
ls command lists the files and directories under current working directory.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
SYNTAX:
The Syntax is
ls [OPTIONS]... [FILE]
OPTIONS:
ld
Lists all the files, directories and their mode, Number of links, owner of the
-l
file, file size, Modified date and time and filename.
-t Lists in order of last modification time.
or
-a Lists all entries including hidden files.
-d Lists directory files instead of contents.
-p Puts slash at the end of each directories.
-u
-i
-ltr
-lSr
W
List in order of last access time.
Display inode information.
List files order by date.
List files order by file size.
EXAMPLE:
TU
ls /
ls -a
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ls -i
7373073 book.gif
7373074 clock.gif
7373082 globe.gif
7373078 pencil.gif
ld
7373080 child.gif
7373081 email.gif
7373076 indigo.gif
or
The above command displays filename with inode value.
ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for
SYNTAX:
The Syntax is
W
desired files. Inode will be different for source and destination.
Link files without questioning the user, even if the mode of target forbids
-f
writing. This is the default if the standard input is not a terminal.
-n Does not overwrite existing files.
-s Used to create soft links.
JN
EXAMPLE:
1. ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt'
and 'file2.txt' will be different.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
2. ln -s nimi nimi1
chown COMMAND:
chown command is used to change the owner / user of the file or directory. This is an admin
ld
command, root user only can change the owner of a file or directory.
SYNTAX:
The Syntax is
or
chown [options] newowner filename/directoryname
OPTIONS:
-R
-c
W
Change the permission on files that are in the subdirectories of the directory
that you are currently in.
Change the permission for each file.
Prevents chown from displaying error messages when it is unable to change
-f
the ownership of a file.
TU
EXAMPLE:
The owner of the 'test.txt' file is root, Change to new user hiox.
The owner of the 'test' directory is root, With -R option the files and subdirectories user
also gets changed.
Here change the owner for the specific 'calc.txt' file only.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
chmod COMMAND:
chmod command allows you to alter / Change access rights to files and directories.
ld
Read Write Execute
User
Group
or
Others
Permission 000
Symbolic Mode W
___ ___ ___
SYNTAX:
TU
The Syntax is
chmod [options] [MODE] FileName
File Permission
# File Permission
0 none
JN
1 execute only
2 write only
3 write and execute
4 read only
5 read and execute
6 read and write
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
OPTIONS:
ld
-c Displays names of only those files whose permissions are being changed
-f Suppress most error messages
-R Change files and directories recursively
-v Output version information and exit.
or
EXAMPLE:
ls -alt
W
This command is used to view your files with what permission they are.
SYNTAX:
The Syntax is
mkdir [options] directories
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
OPTIONS:
ld
EXAMPLE:
1. Create directory:
or
mkdir test
W
2. Create directory and set permissions:
The above command is used to create the directory 'test' and set the read and write
permission.
TU
rmdir COMMAND:
rmdir command is used to delete/remove a directory and its subdirectories.
SYNTAX:
The Syntax is
rmdir [options..] Directory
JN
OPTIONS:
Allow users to remove the directory dirname and its parent directories which
-p
become empty.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
EXAMPLE:
1. To delete/remove a directory
rmdir tmp
ld
rmdir command will remove/delete the directory tmp if the directory is empty.
or
rm -ir tmp
This command recursively removes the contents of all subdirectories of the tmp
directory, prompting you regarding the removal of each file, and then removes the tmp
directory itself.
mv COMMAND:
W
mv command which is short for move. It is used to move/rename file from one directory to
another. mv command is different from cp command as it completely removes the file from the
source and moves to the directory specified, where cp command just copies the content from one
TU
file to another.
SYNTAX:
The Syntax is
mv [-f] [-i] oldname newname
JN
OPTIONS:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
EXAMPLE:
mv file1.txt file2.txt
ld
This command renames file1.txt as file2.txt
2. To move a directory
or
mv hscripts tmp
In the above line mv command moves all the files, directories and sub-directories from
hscripts folder/directory to tmp directory if the tmp directory already exists. If there is no
W
tmp directory it rename's the hscripts directory as tmp directory.
diff COMMAND:
diff command is used to find differences between two files.
SYNTAX:
JN
The Syntax is
diff [options..] from-file to-file
OPTIONS:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
-i Ignore changes in case; consider upper- and lower-case letters equivalent.
Prints in RCS-format, like -f except that each command specifies the number
-n
of lines affected.
or
Output RCS-format diffs; like -f except that each command specifies the
-q
number of lines affected.
-r When comparing directories, recursively compare any subdirectories found.
-s Report when two files are the same.
-w
-y
EXAMPLE:
W
Ignore white space when comparing lines.
Use the side by side output format.
Lets create two files file1.txt and file2.txt and let it have the following data.
TU
This command will compare the file file1.txt with file2.txt ignoring white/blank space
and it will produce the following output.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
2c2
< hscripts.com
---
> HSCRIPTS.com
ld
4d3
< Hioxindia.com
or
diff -by file1.txt file2.txt
This command will compare the files ignoring white/blank space, It is easier to
differentiate the files.
HIOX TEST
hscripts.com
W HIOX TEST
| HSCRIPTS.com
with friend ship with friend ship
Hioxindia.com <
TU
The third line(with friend ship) in file2.txt has more blank spaces, but still the -b ignores
the blank space and does not show changes in the particular line, -y printout the result
side by side.
JN
This command will compare the files ignoring case(upper-case and lower-case) and
displays the following output.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
chgrp COMMAND:
chgrp command is used to change the group of the file or directory. This is an admin
command. Root user only can change the group of the file or directory.
or
SYNTAX:
The Syntax is
chgrp [options] newgroup filename/directoryname
OPTIONS:
-R
W
Change the permission on files that are in the subdirectories of the directory
that you are currently in.
-c Change the permission for each file.
TU
-f Force. Do not report errors.
Hioxindia.com <
EXAMPLE:
The group of 'test' directory is root. With -R, the files and its subdirectories also changes
to newgroup hiox.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
They above command is used to change the group for the specific file('calc.txt') only.
About wc
ld
Short for word count, wc displays a count of lines, words, and characters in a file.
Syntax
or
-c Count bytes.
-m Count characters.
-C
-l
-w
Same as -m.
Count lines.
W
Count words delimited by white space characters or new line characters.
Delimiting characters are Extended Unix Code (EUC) characters from any code
TU
set defined by iswspace()
Examples
wc myfile.txt - Displays information about the file myfile.txt. Below is an example of the output.
JN
5 13 57 myfile.txt
5 = Lines
13 = Words
57 = Characters
About split
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Syntax
ld
split -b n [k | m] [ -a suffixlength ] [ file [name]]
or
-a Use suffixlength letters to form the suffix portion of the filenames of the split
suffixlength file. If -a is not specified, the default suffix length is 2. If the sum of the name
operand and the suffixlength option-argument would create a filename exceeding
-b n
W
NAME_MAX bytes, an error will result; split will exit with a diagnostic message
and no files will be created.
File The path name of the ordinary file to be split. If no input file is given or file is -,
the standard input will be used.
name The prefix to be used for each of the files resulting from the split operation. If no
name argument is given, x will be used as the prefix of the output files. The
combined length of the basename of prefix and suffixlength cannot exceed
JN
Examples
split -b 22 newfile.txt new - would split the file "newfile.txt" into three separate files called
newaa, newab and newac each file the size of 22.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
split -l 300 file.txt new - would split the file "newfile.txt" into files beginning with the name
"new" each containing 300 lines of text each
ld
Syntax
or
settime [ -f ref_file ] file
-a Change the access time of file. Do not change the modification time unless -m is
also specified.
-c
W
Do not create a specified file if it does not exist. Do not write any diagnostic
messages concerning this condition.
-m Change the modification time of file. Do not change the access time unless -a is
also specified.
TU
-r ref_file Use the corresponding times of the file named by ref_file instead of the current
time.
-t time Use the specified time instead of the current time. time will be a decimal number
of the form:
[[CC]YY]MMDDhhmm [.SS]
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
-f ref_file Use the corresponding times of the file named by ref_file instead of the current
time.
ld
File A path name of a file whose times are to be modified.
Examples
or
settime myfile.txt
touch newfile.txt
W
Creates a file known as "newfile.txt", if the file does not already exist. If the file already exists
the accessed / modification time is updated for the file newfile.txt
About comm
TU
Select or reject lines common to two files.
Syntax
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Examples
The above example would compare the two files myfile1.txt and myfile2.txt.
ld
Process utilities:
or
ps COMMAND:
ps command is used to report the process status. ps is the short name for Process Status.
SYNTAX:
The Syntax is
ps [options]
OPTIONS:
W
List information about all processes most frequently requested: all those
TU
-a
except process group leaders and processes not associated with a terminal..
-A or e List information for all processes.
-d List information about all processes except session leaders.
-e List information about every process now running.
-f Generates a full listing.
-j Print session ID and process group ID.
JN
1. ps
Output:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
In the above example, typing ps alone would list the current running processes.
ld
2. ps -f
Output:
or
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
nirmala 2639 2540 0 15:51 pts/1 00:00:00 ps -f
kill COMMAND:
W
Displays full information about currently running processes.
SYNTAX:
TU
The Syntax is
kill [-s] [-l] %pid
OPTIONS:
Specify the signal to send. The signal may be given as a signal name or
-s
JN
number.
Write all values of signal supported by the implementation, if no operand is
-l
given.
-pid Process id or job id.
-9 Force to kill a process.
EXAMPLE:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
To know group id or job id of the background task.
jobs -l
It will list the background jobs with its job id as,
or
xmms 3956
kmail 3467
About nice
Syntax
The super-user may run commands with priority higher than normal by using a
negative increment such as -10. A negative increment assigned by an
unprivileged user is ignored.
command The name of a command that is to be invoked. If command names any of the
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Examples
ld
nice +13 pico myfile.txt - runs the pico command on myfile.txt with an increment of +13.
About at
or
Schedules a command to be ran at a particular time, such as a print job late at night.
Syntax
atq
W
lists the user's pending jobs, unless the user is the superuser; in that case, everybody's jobs
are listed. The format of the output lines (one for each job) is: Job number, date, hour, job
class.
at [-c | -k | -s] [-f filename] [-q queuename] [-m] -t time [date] [-l] [-r]
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
-t time Specifies at what time you want the command to be ran. Format hh:mm. am / pm
indication can also follow the time otherwise a 24-hour clock is used. A timezone
name of GMT, UCT or ZULU (case insensitive) can follow to specify that the
time is in Coordinated Universal Time. Other timezones can be specified using
the TZ environment variable. The below quick times can also be entered:
ld
midnight - Indicates the time 12:00 am (00:00).
noon - Indicates the time 12:00 pm.
now - Indicates the current day and time. Invoking at - now will submit submit
or
an at-job for potentially immediate execution.
date Specifies the date you wish it to be ran on. Format month, date, year. The
following quick days can also be entered:
today
W - Indicates
tomorrow - Indicates the day following the current day.
the current day.
Examples
at -m 01:35 < atjob = Run the commands listed in the 'atjob' file at 1:35AM, in addition all
output that is generated from job mail to the user running the task. When this command has been
successfully enter you should receive a prompt similar to the below example.
JN
at -l = This command will list each of the scheduled jobs as seen below.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
or
ld
If you wish to create a job that is repeated you could modify the file that executes the commands
with another command that recreates the job or better yet use the crontab command.
Note: Performing just the at command at the prompt will give you an error "Garbled Time", this
or
is a standard error message if no switch or time setting is given.
Filters:
more COMMAND:
W
more command is used to display text in the terminal screen. It allows only backward
movement.
SYNTAX:
The Syntax is
TU
more [options] filename
OPTIONS:
-n Specify how many lines are printed in the screen for a given file.
+n Starts up the file from the given number.
EXAMPLE:
1. more -c index.php
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
2. more -3 index.php
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND:
head command is used to display the first ten lines of a file, and also specifies how many lines
ld
to display.
SYNTAX:
The Syntax is
or
head [options] filename
OPTIONS:
-n
-n number
W
To specify how many lines you want to display.
The number option-argument must be a decimal integer whose sign affects
the location in the file, measured in lines.
The number option-argument must be a decimal integer whose sign affects
-c number
the location in the file, measured in bytes.
TU
EXAMPLE:
1. head index.php
2. head -5 index.php
JN
3. head -c 5 index.php
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays last
10 lines of a file.
SYNTAX:
ld
The Syntax is
tail [options] filename
OPTIONS:
or
-l To specify the units of lines.
-b To specify the units of blocks.
-n To specify how many lines you want to display.
-c number
-n number
W
The number option-argument must be a decimal integer whose sign affects the
location in the file, measured in bytes.
The number option-argument must be a decimal integer whose sign affects the
location in the file, measured in lines.
EXAMPLE:
TU
1. tail index.php
2. tail -2 index.php
JN
3. tail -n 5 index.php
4. tail -c 5 index.php
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
cut COMMAND:
cut command is used to cut out selected fields of each line of a file. The cut command uses
delimiters to determine where to split fields.
ld
SYNTAX:
The Syntax is
cut [options]
or
OPTIONS:
Output:
TU
Thi
Output:
The above command is used to split the fields using delimiter and cut the first two fields.
paste COMMAND:
paste command is used to paste the content from one file to another file. It is also used to set
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
SYNTAX:
The Syntax is
paste [options]
ld
OPTIONS:
or
-d Reuse characters from LIST instead of TABs .
EXAMPLE:
1. paste test.txt>test1.txt
W
Paste the content from 'test.txt' file to 'test1.txt' file.
2. ls | paste - - - -
List all files and directories in four columns for each line.
TU
sort COMMAND:
sort command is used to sort the lines in a text file.
SYNTAX:
The Syntax is
sort [options] filename
JN
OPTIONS:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
EXAMPLE:
1. sort test.txt
ld
2. sort -r test.txt
Sorts the 'test.txt' file in reverse order and prints result in the screen.
or
About uniq
Syntax
-c
W
uniq [-c | -d | -u ] [ -f fields ] [ -s char ] [-n] [+m] [input_file [ output_file ] ]
Precede each output line with a count of the number of times the line occurred in
the input.
TU
-d Suppress the writing of lines that are not repeated in the input.
-f fields Ignore the first fields fields on each input line when doing comparisons, where
fields is a positive decimal integer. A field is the maximal string matched by the
basic regular expression:
JN
[[:blank:]]*[^[:blank:]]*
If fields specifies more fields than appear on an input line, a null string will be
used for comparison.
-s char Ignore the first chars characters when doing comparisons, where chars is a
positive decimal integer. If specified in conjunction with the -f option, the first
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
chars characters after the first fields fields will be ignored. If chars specifies more
characters than remain on an input line, a null string will be used for comparison.
ld
input_file A path name of the input file. If input_file is not specified, or if the input_file is -
, the
standard input will be used.
or
output_file A path name of the output file. If output_file is not specified, the standard output
will be used. The results are unspecified if the file named by output_file is the
file named by input_file.
Examples W
uniq myfile1.txt > myfile2.txt - Removes duplicate lines in the first file1.txt and outputs the
results to the second file.
About tr
TU
Translate characters.
Syntax
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Examples
echo "12345678 9247" | tr 123456789 computerh - this example takes an echo response of
'12345678 9247' and pipes it through the tr replacing the appropriate numbers with the letters. In
this example it would return computer hope.
ld
tr -cd '\11\12\40-\176' < myfile1 > myfile2 - this example would take the file myfile1 and strip
all non printable characters and take that results to myfile2.
General Commands:
or
date COMMAND:
date command prints the date and time.
SYNTAX:
The Syntax is
W
date [options] [+format] [date]
OPTIONS:
TU
Slowly adjust the time by sss.fff seconds (fff represents fractions of a second).
-a This adjustment can be positive or negative.Only system admin/ super user
can adjust the time.
-
Sets the time and date to the value specfied in the datestring. The datestr may
s date-
contain the month names, timezones, 'am', 'pm', etc.
JN
string
-u Display (or set) the date in Greenwich Mean Time (GMT-universal time).
Format:
%a Abbreviated weekday(Tue).
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
%A Full weekday(Tuesday).
ld
%D Date in the format %m/%d/%y.
or
%p String to indicate a.m. or p.m.
%t
%V
EXAMPLE:
Tab space. W
Week number in year (01-52); start week on Monday.
1. date command
TU
date
The above command will print Wed Jul 23 10:52:34 IST 2008
date -V
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
The above command will print Wed Oct 08 11:37:23 IST 2008
who COMMAND:
who command can list the names of users currently logged in, their terminal, the time they
or
have been logged in, and the name of the host from which they have logged in.
SYNTAX:
The Syntax is
who [options] [file]
OPTIONS:
W
Print the username of the invoking user, The 'am' and 'i' must be space
am i
separated.
TU
-m Same as who am i.
-q Prints only the usernames and the user count/total no of users logged in.
-T,-w Include user's message status in the output.
EXAMPLE:
1. who -uH
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Output:
This sample output was produced at 11 a.m. The "." indiacates activity within the last
ld
minute.
2. who am i
or
who am i command prints the user name.
echo COMMAND:
echo command prints the given input string to standard output.
SYNTAX:
The Syntax is
echo [options..] [string]
W
OPTIONS:
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
\v vertical tab
EXAMPLE:
or
1. echo command
2. To use backspace:
echo -e "hscripts\tHiox\tIndia"
passwd COMMAND:
passwd command is used to change your password.
SYNTAX:
The Syntax is
passwd [options]
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
OPTIONS:
ld
Deletes password for name. The login name will not be prompted for
-d
password.
Force the user to change password at the next login by expiring the password
-f
for name.
or
EXAMPLE:
1. passwd
W
Entering just passwd would allow you to change the password. After entering passwd you
will receive the following three prompts:
Current Password:
New Password:
Confirm New Password:
TU
Each of these prompts must be entered correctly for the password to be successfully
changed.
pwd COMMAND:
pwd - Print Working Directory. pwd command prints the full filename of the current working
directory.
JN
SYNTAX:
The Syntax is
pwd [options]
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
OPTIONS:
ld
1. Displays the current working directory.
or
pwd
If you are working in home directory then, pwd command displays the current working
directory as /home.
cal COMMAND:
W
cal command is used to display the calendar.
SYNTAX:
The Syntax is
TU
cal [options] [month] [year]
OPTIONS:
1. cal
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Output:
September 2008
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
ld
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
or
cal command displays the current month calendar.
2. cal -3 5 2008
Output:
April 2008
W
May 2008 June 2008
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 1 2 3 1 2 3 4 5 6 7
6 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13 14
TU
13 14 15 16 17 18 19 11 12 13 14 15 16 17 15 16 17 18 19 20 21
20 21 22 23 24 25 26 18 19 20 21 22 23 24 22 23 24 25 26 27 28
27 28 29 30 25 26 27 28 29 30 31 29 30
Here the cal command displays the calendar of April, May and June month of year 2008.
login Command
JN
Syntax
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
-d device login accepts a device option, device. device is taken to be the path name of the
TTY port login is to operate on. The use of the device option can be expected to
improve login performance, since login will not need to call ttyname. The -d
option is available only to users whose UID and effective UID are root. Any
ld
other attempt to use -d will cause login to quietly exit.
-h hostname | Used by in.telnetd to pass information about the remote host and terminal type.
terminal
or
-r hostname Used by in.rlogind to pass information about
the remote host.
Examples W
login computerhope.com - Would attempt to login to the computerhope domain.
uname command
Syntax
uname [-a] [-i] [-m] [-n] [-p] [-r] [-s] [-v] [-X] [-S systemname]
-m Print the machine hardware name (class). Use of this option is discouraged; use
uname -p instead.
-n Print the nodename (the nodename is the name by which the system is known to
a communications network).
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
-X Print expanded system information, one information
element per line, as expected by SCO Unix. The
displayed information includes:
or
system name, node, release, version, machine, and number of CPUs.
BusType, Serial, and Users (set to "unknown" in Solaris)
OEM# and Origin# (set to 0 and 1, respectively)
-S
systemname
W
The nodename may be changed by specifying a system name argument. The
system name argument is restricted to SYS_NMLN characters. SYS_NMLN is
an implementation specific value defined in <sys/utsname.h>. Only the super-
user is allowed
this capability.
TU
Examples
uname -arv
List the basic system information, OS release, and OS version as shown below.
JN
uname -p
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
SED:
What is sed?
ld
Use sed to:
Automatically perform edits on file(s)
Simplify doing the same edits on multiple files
Write conversion programs
or
W
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
sed Operation
W
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Note: input file is unchanged
address determines which lines in the input file are to be processed by the command(s)
or
if no address is specified, then the command is applied to each input line
address types:
Single-Line address
Range address
Nested address
W
Set-of-Lines address
Single-Line Address
Examples:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Set-of-Lines Address
ld
lines may or may not be consecutives
Examples:
or
sed -e ‘/key/ s/more/other/’ input-file
Range Address W
Defines a set of consecutive lines
Format:
start-addr,end-addr (inclusive)
TU
Examples:
10,50 line-number,line-number
10,/R.E/ line-number,/RegExp/
JN
/R.E./,10 /RegExp/,line-number
/R.E./,/R.E/ /RegExp/,/RegExp/
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
BEGIN
Line 1 of input
ld
Line 2 of input
Line3 of input
END
or
Line 4 of input
Line 5 of input
Nested Address
W
Nested address contained within another address
TU
Example:
20,30{
/^$/ p
JN
Address with !
instruction will be applied to all lines that do not match the address
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Example:
ld
sed commands
or
Line Number
W
line number command (=) writes the current line number before each matched/output line
Examples:
TU
modify commands
JN
Insert Command: i
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
adds one or more lines directly to the output before the address:
inserted “text” never appears in sed’s pattern space
cannot be used with a range address; can only be used with the single-line and set-
of-lines address types
Syntax:
ld
[address] i\
text
or
Append Command: a
adds one or more lines directly to the output after the address:
Syntax:
W
Similar to the insert command (i), append cannot be used with a range address.
Appended “text” does not appear in sed’s pattern space.
[address] a\
TU
text
Change Command: c
Syntax:
[address1[,address2]] c\
text
Delete Command: d
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Syntax:
ld
[address1[,address2]] d
or
Syntax:
[addr1][,addr2] s/search/replace/[flags]
flags:
W
search string can be regular expression
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
Substitution Back References
TU
JN
$ cat datafile
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
TB Savage 4.4 .84 5 20
or
Ann Stephens 5.7 .94 5 13
Charles Main
Sharon Gray
3.0
5.3
W.98
.97
3
5
34.5
23.5
Syntax:
[addr1][,addr2]y/a/b/
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Example:
ld
$ sed -e ‘1,10y/abcd/wxyz/’ datafile
or
Input (next) Command: n and N
W
Forces sed to read the next input line
Copies the contents of the pattern space to output
TU
Deletes the current line in the pattern space
Refills it with the next input line
Continue processing
N (uppercase) Command
adds the next input line to the current contents of the pattern space
useful when applying patterns to two or more lines at the same time
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
prints the contents of the pattern space up to and including a new line character
any text following the first new line is not printed
ld
shows special characters (e.g. tab, etc)
The octal dump command (od -c) can be used to produce similar result
Hold Space
or
temporary storage area
h, H
W
4 commands that can be used to move text back and forth between the pattern space and
g, G
TU
File commands
allows to read and write from/to file while processing standard input
read: r command
write: w command
JN
Syntax: r filename
queue the contents of filename to be read and inserted into the output stream at
the end of the current cycle, or when the next input line is read
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Syntax: w filename
or
all w commands which refer to the same filename are output through the same
FILE stream
Syntax: [addr1][,addr2]b[label]
Branch label
:mylabel
Syntax: [addr]q
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Same as:
ld
% head -50 datafile
AWK
or
What is awk?
awk operation:
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Basic awk Syntax
W
awk [options] ‘script’ file(s)
TU
awk [options] –f scriptfile file(s)
Options:
pattern {action}
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Example:
ld
prints all lines containing string “for” in testfile
or
A field is a unit of data in a line
Each field is separated from the other fields by the field separator
default field separator is whitespace
A record is the collection of fields in a line
W
A data file is made up of records
Buffers
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
awk supports two types of buffers:
or
field buffer:
one for each fields in the current record.
names: $1, $2, …
record buffer : W
$0 holds the entire record
% cat emps
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Billy Black 1683 9/23/44 336500
or
2 Mary Adams 5346 11/4/63 28765
% cat emps
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
% cat em2
ld
Tom Jones:4424:5/12/66:543354
Mary Adams:5346:11/4/63:28765
Sally Chang:1654:7/22/54:650000
or
Billy Black:1683:9/23/44:336500
awk Scripts
W
awk scripts are divided into three major parts:
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
awk Scripts
BEGIN: pre-processing
performs processing that must be completed before the file processing starts (i.e.,
before awk starts reading records from the input file)
useful for initialization tasks such as to initialize variables and to create report
ld
headings
BODY: Processing
contains main processing logic to be applied to input records
or
like a loop that processes input data one record at a time:
if a file contains 100 records, the body will be executed 100 times, one for
each record
END: post-processing
W
contains logic to be executed after all input data have been processed
logic such as printing report grand total should be performed in this part of the
script
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Categories of Patterns
ld
or
Expression Pattern types
match
W
entire input record
expression operators
arithmetic
relational
logical
JN
% cat employees2
Tom Jones:4424:5/12/66:543354
Mary Adams:5346:11/4/63:28765
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
ld
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
or
% cat datafile
western WE
southwest SW
Sharon Gray
W
Lewis Dalsass
5.3
2.7
.97
.8
5 23
2 18
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
northwest NW
ld
southwest SW
southern SO
north NO
or
central CT
northwest
southwest
W
southern
TU
southeast
northeast
north
Arithmetic Operators
JN
+ Add x+y
- Subtract x–y
* Multiply x*y
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
/ Divide x/y
% Modulus x%y
^ Exponential x^y
ld
Example:
Relational Operators
or
Operator Meaning Example
<=
== Equal to
W
Less than or equal x<=y
x == y
!= Not equal to x != y
TU
Logical Operators
|| Logical OR a || b
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
! NOT !a
Examples:
% awk '($2 > 5) && ($2 <= 15) {print $0}' file
ld
% awk '$3 == 100 || $4 > 50' file
Range Patterns
or
Syntax:
awk Actions
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
awk expressions W
Expression is evaluated and returns value
consists of any combination of numeric and string constants, variables, operators,
functions, and regular expressions
Can involve variables
TU
awk variables
Variable names start with a letter, followed by letters, digits, and underscore
Variables come into existence the first time they are referenced; therefore, they do not
need to be declared before use
All variables are initially created as strings and initialized to a null string “”
awk Variables
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Format:
variable = expression
Examples:
ld
% awk '$1 ~ /Tom/
or
% awk '$4 == "CA" {$4 = "California"; print $0}' filename
=
W
assign result of right-hand-side expression to
left-hand-side variable
++ Add 1 to variable
TU
Awk example
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
File: grades
john 85 92 78 94 88
andrea 89 90 75 90 86
ld
jasper 84 88 80 92 84
or
{ total = $2 + $3 + $4 + $5 + $6
avg = total / 5
Run as:
W
awk –f average grades
TU
Output Statements
printf
JN
sprintf
Function: print
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
default OFS is blank
Print control characters are allowed:
\n \f \a \t \\ …
or
print example
john 85 92 78 94 88
andrea 89 90 75 90 86
andrea 89 90 75 90 86
john 85 92 78 94 88
andrea 89 90 75 90 86
JN
> “file”
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
>> “file”
| “command”
ld
print Example
or
% cat file
john 85
andrea 89
jasper 84
W
% awk '{print $1,$2 | "sort"}' grades
andrea 89
TU
jasper 84
john 85
jasper 84
john 85
andrea 89
% date
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
% date |
ld
Month: Nov
Year: 2008
or
Syntax:
Format specifiers
%c single character
%s string of characters
%o octal number
%x hexadecimal number
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
%c printf("The character is %c \n", x)
or
output: The character is A
%s
W output: The boy is 15 years old
output: z is 2.300
%10s
%7d
%10.4f
%-20s
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
meaning:
width of field, field is printed right justified
precision: number of digits after decimal point
“-” will left justify
ld
Syntax:
or
Works like printf, but does not produce output
Instead it returns formatted string
Example:
{
W
text = sprintf("1: %d – 2: %d", $1, $2)
print text
TU
tolower(string)
toupper(string)
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
103:sway bar:49.99
ld
101:propeller:104.99
104:fishing line:0.99
or
106:cup holder:2.49
107:cooler:14.89
112:boat cover:120.00
109:transom:199.00
W
110:pulley:9.88
TU
105:mirror:4.99
108:wheel:49.99
111:lock:31.00
102:trailer hitch:97.95
JN
Marine Parts R Us
Main catalog
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
======================================
ld
103 sway bar 49.99
or
106 cup holder 2.49
108
109
wheel
transom
W
49.99
199.00
======================================
JN
BEGIN {
FS= ":"
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
print "======================================"
or
printf("%3d\t%-20s\t%6.2f\n", $1, $2, $3)
count++
END {
W
print "======================================"
TU
awk Array
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Arrays in awk
Syntax:
ld
arrayName[index] = value
Examples:
or
list[1] = "one"
list[2] = "three"
W
list["other"] = "oh my !"
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
divides string into pieces separated by fieldsep, and stores the pieces in array
if the fieldsep is omitted, the value of FS is used.
Example:
split("auto-da-fe", a, "-")
ld
sets the contents of the array a as follows:
a[1] = "auto"
or
a[2] = "da"
a[3] = "fe"
input file:
W
TU
JN
output:
summary of category sales
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
Illustration: process each input line
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Example: complete program
% cat sales.awk
or
{
deptSales[$2] += $3
END {
W
for (x in deptSales)
TU
print x, deptSales[x]
Conditional
if-else
Repetition
for
with counter
with array index
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
while
do-while
also: break, continue
if Statement
ld
Syntax:
if (conditional expression)
or
statement-1
else
statement-2
Example:
if ( NR < 3 )
W
print $2
TU
else
print $3
for Loop
Syntax:
JN
statement
Example:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
total += $i
count++
ld
}
Syntax:
or
for (var in array)
statement
Example:
for (x in deptSales)
W
{
TU
print x, deptSales[x]
while Loop
Syntax:
JN
statement
Example:
i=1
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
print i, $i
ld
i++
do-while Loop
or
Syntax:
do
statement
while (condition)
W
statement is executed at least once, even if condition is false at the beginning
TU
Example:
i=1
do {
print $0
JN
i++
break
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
exits loop
continue
ld
"Unit-II - Shell Programming"
or
Shell Programming
The shell has similarities to the DOS command processor Command.com (actually
Dos was design as a poor copy of UNIX shell), it's actually much more powerful,
really a programming language in its own right.
W
A shell is always available on even the most basic UNIX installation. You have to go
through the shell to get other programs to run. You can write programs using the shell.
You use the shell to administrate your UNIX system. For example:
ls -al | more
is a short shell program to get a long listing of the present directory and route the
output through the more command.
TU
What is a Shell?
A shell is a program that acts as the interface between you and the UNIX system,
allowing you to enter commands for the operating system to execute.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Pipes and Redirection
Pipes connect processes together. The input and output of UNIX programs can be
redirected.
Redirecting Output
W
The > operator is used to redirect output of a program. For example:
ls -l > lsoutput.txt
redirects the output of the list command from the screen to the file lsoutput.txt.
ps >> lsoutput.txt
Redirecting Input
Pipes
JN
We can connect processes together using the pipe operator ( | ). For example, the
following program means run the ps program, sort its output, and save it in the file
pssort.out
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
You can type in a sequence of commands and allow the shell to execute them
interactively, or youu can sotre these commands in a file which you can invoke as a
program.
Interactive Programs
ld
A quick way of trying out small code fragments is to just type in the shell script on the
command line. Here is a shell program to compile only files that contain the string
POSIX.
or
Creating a Script
W
To create a shell script first use a text editor to create a file containing the commands.
For example, type the following commands and save them as first.sh
TU
JN
The line
#!/bin/sh
is special and tells the system to use the /bin/sh program to execute this program.
The command
JNTU World Page 99
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
exit 0
Causes the script program to exit and return a value of 0, which means there were not
errors.
There are two ways to execute the script. 1) invoke the shell with the name of the
ld
script file as a parameter, thus:
/bin/sh first.sh
Or 2) change the mode of the script to executable and then after execute it by just
typing its name.
or
chmod +x first.sh
first.sh
Actually, you may need to type:
./first.sh
to make the file execute unles the path variable has your directory in it.
Shell Syntax
W
The modern UNIX shell can be used to write quite large, structured programs.
Variables
Variables are generally created when you first use them. By default, all variables are
TU
considered and stored as strings. Variable names are case sensitive.
JN
Quoting
Normally, parameters are separated by white space, such as a space. Single quot
marks can be used to enclose values containing space(s). Type the following into a
file called quot.sh
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
make sure to make it executable by typing the command:
or
< chmod a+x quot.sh
The results of executing the file is:
How It Works
W
The variable myvar is created and assigned the string Hi there. The content of the
variable is displyed using the echo $. Double quotes don't effect echoing the value.
Single quotes and backslash do.
TU
Environment Variables
When a shell starts, some variables are initialized from values in the environment.
Here is a sample of some of them.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Parameter Variables
W
If your script is invoked with parameters, some additional variables are created.
TU
The following shows the difference between using the variable $* and $@
JN
notice that the first line of the above has a space between the firsr ' and the second '.
Now try your hand at typing a shell script
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
make sure to make it executable by typing the command:
or
< chmod a+x try_variables
Execute the file with parameters by typing:
try_variables foo bar baz
The results of executing the file is:
W
TU
How It Works
It creates the variable salutation, displays its value, and some parameter variables.
Conditions
All programming languages have the ability to test conditions and perform different
actions based on those conditions. A shell script can test the exit code of any
JN
command.
The test, or []Command
Here is how to check for the existance of the file fred.c using the test and using the []
command.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
You can even place the then on the same line as the if, if youu add a semicolon before
the word then.
or
Here are the conditon types that can be used with the test command. There are string
comparison.
W
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Control Structures
or
The shell has a set of control structures.
if
The if statement is vary similar other programming languages except it ends with a fi.
if condition
then
else
W
statements
statements
fi
TU
elif
the elif is better known as "else if". It replaces the else part of an if statement with
another if statement. You can try it out by using the following script.
#!/bin/sh
if [ $timeofday = "yes" ]
then
echo "Good morning"
elif [ $timeofday = "no" ]; then
echo "Good afternoon"
else
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
exit 0
How It Works
ld
The above does a second test on the variable timeofday if it isn't equal to yes.
A Problem with Variables
or
if [ $timeofday = "yes" ]
looks like
if [ = "yes" ]
which is illegal. This problem can be fixed by using double quotes around the variable
name.
.
for
W
if [ "$timeofday" = "yes" ]
The for construct is used for looping through a range of values, which can be any set
of strings. The syntax is:
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
How It Works
The above example creates the variable foo and assigns it a different value each time
around the for loop.
How It Works
Here is another script which uses the $(command) syntax to expand a list to chap3.txt,
ld
chap4.txt, and chap5.txt and print the files.
#!/bin/sh
or
lpr $file
done
while
While loops will loop as long as some condition exist. OF course something in the
W
body statements of the loop should eventually change the condition and cause the loop
to exit. Here is the while loop syntax.
while condition do
statements
done
Here is a whil loop that loops 20 times.
TU
#!/bin/sh
foo=1
done
exit 0
How It Works
The above script uses the [ ] command to test foo for <= the value 20. The line
foo=$(($foo+1))
increments the value of foo each time the loop executes..
JNTU World Page 107
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
until
The until statement loops until a condition becomes true! Its syntax is:
until condition
do
statements
ld
done
Here is a script using until.
#!/bin/sh
or
do
sleep 60
done
echo -e \\a
W
echo "**** $1 has just loogged in ****"
exit 0
case
TU
The case statement allows the testing of a variable for more then one value. The case
statement ends with the word esac. Its syntax is:
case variable in
pattern [ | pattern] ...) statements;;
pattern [ | pattern] ...) statements;;
...
esac
Here is a sample script using a case statement:
JN
#!/bin/sh
case "$timeofday" in
"yes") echo "Good Morning";;
"no" ) echo "Good Afternoon";;
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
exit 0
ld
How It Works
The value in the varaible timeofday is compared to various strings. When a match is
made, the associated echo command is executed.
or
Here is a case where multiple strings are tested at a time, to do the some action.
case "$timeofday" in
"yes" | "y" | "yes" | "YES" ) echo "good Morning";;
"n"* | "N"* ) <echo "Good Afternoon";;
* ) < echo "Sorry, answer not recognized";;
How It Works
esac
W
The above has sever strings tested for each possible statement.
Here is a case statement that executes multiple statements for each case.
TU
case "$timeofday" in
"yes" | "y" | "Yes" | "YES" )
echo "Good Morning"
echo "Up bright and early this morning"
;;
[nN]*)
echo "Good Afternoon"
;;
JN
*)
echo "Sorry, answer not recognized"
echo "Please answer yes or noo"
exit 1
;;
esac
How It Works
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
When a match is found to the variable value of timeofday, all the statements up to the
;; are executed.
Lists
ld
The AND List
or
Her is a sample AND list:
#!/bin/sh
touch fine_one
rm -f file_two
then
else
W
if [ -f file_one ] && echo "hello" && [ -f file_two ] && echo " there"
exit 0
How It Works
The touch command creates an empty file. the rm come remove a file. So, before we
start, file_one exists and file_two doesn't. The AND list finds the file_one, and echos
the word hello, but it doesn't find the file file_two. Therefore the overall if fails and
the else clause is executed.
JN
The OR List
The OR list construct allows us to execute a series of commands until one succeeds!
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
exit 0
How It Works
The above script removes the file file_one, then test for and fails to find the file_one,
or
but does successfully echo hello. It then executes the then statement echoing in if.
Statement Blocks
Functions W
You can define functions inthe shell. The syntax is:
function_name () {
statements
}
Here is a sample function and its execution.
TU
#!/bin/sh
foo() {
echo "Function foo is executing"
}
exit 0
How It Works
When the above script runs, it defines the funcion foo, then script echos script
starting, then it runs the functions foo which echos Function foo is executing, then it
echo script ended.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
#!/bin/sh
yes_or_no() {
echo "Parameters are $*"
while true
ld
do
echo -n "Enter yes or no"
read x
case "$x" in
y | yes ) return 0;;
or
n | no ) return 1;;
* ) echo "Answer yes or no"
esac
done
}
W
echo "Original parameters are $*"
exit 0
How It Works
Commands
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
You can execute normal command and built-in commands from a shell script. Built-in
commands are defined and only run inside of the script.
break
It is used to escape from an enclosing for, while or until loop before the controlling
condition has been met.
ld
The : Command
The colon command is a null command. It can be used for an alias for true..
continue
or
The continue command makes the enclosing for, while, or until loop continue at the
next iteration.
The . Command
.
W
The dot command executes the command in the current shell:
. shell_script
echo
The echo command simply outputs a string to the standard output device followed by
TU
a newline character.
eval
The exec command can replace the current shell with a different program. It can also
JN
The exit command causes the script to exit with exit code n. An exit code of 0 means
success. Here are some other codes.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
export
ld
The export command makes the variable named as its parameter available in
subshells.
expr
or
The expr command evaluates its arguments as an expression.
x = `expr $x + 1`
Here are some of its expression evaluations
W
TU
printf
The printf command is only available in more recent shells. It works similar to the
echo command. Its general form is:
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
return
W
The return command causes functions to return. It can have a value parameter which it
returns.
set
The set command sets the parameter variables for the shell.
TU
shift
The shift command moves all the parameters variables down by one, so $2 becomes
$1, $3 becomes $2, and so on.
trap
The trap command is used for secifying the actions to take on receipt of signals. It
JN
syntax is:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
How It Works
The try it out section has you type in a shell script to test the trap command. It creates
a file and keeps saying that it exists until youu cause a control-C interrupt. It does it
or
all again.
unset
Command Execution
W
The result of $(command) is simply the output string from the command, which is
then available to the script.
Arithmetic Expansion
The $((...)) is a better alternative to the expr command, which allows simple
TU
x=$(($x+1))
Parameter Expansion
#!/bin/sh
JN
for i in 1 2
do
my_secret_process ${i}_tmp
done
Here are some of the parameter expansion
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
How It Works
or
The try it out exercise uses parameter expansion to demonstrate how parameter
expansion works.
Here Documents
W
A here document is a special way of passing input to a command from a shell script.
The document starts and ends with the same leader after <<. For example:
#!/bin/sh
Debugging Scripts
When an error occurs in a script, the shell prints out the line number with an error.
JN
You can use the set command to set various shell option. Here are some of them.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Putting It All Together
or
Requirements
The system should store basic information about each CD, search for CDs, and update
or add new CDs.
Design
W
The three requirements--updating, searching and displaying the CD data--suggest that
a simple menu willbe adequate. Here is the example titles file.
TU
Notes
The code for the CD database is included in the try it out section. The trap command
allows the user to use Ctrl-C.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Summary
By the time you enter the CD database application, you will know that programs can
be written using just the shell language. The shell is used for much of Linux system
administration.
ld
Chapter Outline
Working with Files
or
UNIX File Structure
Directories
Files and Devices
System Calls and Device Drivers
Library Functions
W
Low-level File Access
Other System Calls for Managing Files
The Standard I/O Library
Formatted Input and Output
Other Stream Functions
Stream Errors
Stream and File Descriptors
File and Directory Maintenance
TU
Scanning Directories
Errors
Advanced
Summary
JN
Lecture Notes
Working with Files
In this chapter we learn how to create, open, read, write, and close files.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Programs can use disk files, serial ports, printers and other devices in the exactly the
same way as they would use a file.
ld
Directories
As well as its contents, a file has a name and 'administrative information', i.e. the file's
creation/modification date and its permissions.
or
The permissions are stored in the inode, which also contains the length of the file and
where on the disc it's stored.
A directory is a file that holds the inodes and names of other files.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Even hardware devices are represented (mapped) by files in UNIX. For example,
as root, you mount a CD-ROM drive as a file,
ld
(keyboard and screen, or window) of a process.
/dev/null - This is the null device. All output written to this device is discarded.
or
System calls are provided by UNIX to access and control files and devices.
W
The system calls to access the device drivers include:
TU
Library Functions
To provide a higher level interface to device and disk files, UNIIX provides a number
of standard libraries.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Low-level File Access
W
Each running program, called a process, has associated with it a number of file
descriptors.
TU
When a program starts, it usually has three of these descriptors already opened. These
are:
JN
The write system call arranges for the first nbytes bytes from buf to be written to the
file associated with the file descriptor fildes.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Here is how to run the program and its output.
$ simple_write
Here is some data
read
$ W
TU
The read system call reads up to nbytes of data from the file associated with the file
decriptor fildes and places them in the data area buf.
This program, simple_read.c, copies the first 128 bytes of the standard input to the
standard output.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
If you run the program, you should see:
To create a new file descriptor we need to use the open system call.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The name of the file or device to be opened is passed as a parameter, path, and
the oflags parameter is used to specify actions to be taken on opening the file.
The oflags are specified as a bitwise OR of a mandatory file access mode and other
optional modes. The open call must specify one of the following file access modes:
ld
or
The call may also include a combination (bitwise OR) of the following optional
W
modes in the oflags parameter:
TU
Initial Permissions
When we create a file using the O_CREAT flag with open, we must use the three
JN
parameter form. mode, the third parameter, is made form a bitwise OR of the flags
defined in the header file sys/stat.h. These are:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Foe example
W
Has the effect of creating a file called myfile, with read permission for the owner and
execute permission for others, and only those permissions.
TU
umask
The umask is a system variable that encodes a mask for file permissions to be used
when a file is created.
You can change the variable by executing the umask command to supply a new
value.
JN
The value is a three-digit octal value. Each digit is the results of ANDing values from
1, 2, or 4.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
For example, to block 'group' write and execute, and 'other' write, the umask would
be:
TU
JN
Values for each digit are ANDed together; so digit 2 will have 2 & 1, giving 3. The
resulting umask is 032.
close
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
We use close to terminate the association between a file descriptor, fildes, and its file.
ld
ioctl
or
ioctl is a bit of a rag-bag of things. It provides an interface for controlling the behavior
of devices, their descriptors and configuring underlying services.
descriptor fildes.
W
ioctl performs the function indicated by cmd on the object referenced by the
We now know enough about the open, read and write system calls to write a low-
level program, copy_system.c, to copy one file to another, character by character.
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
Running the program will give the following:
TU
We used the UNIX time facility to measure how long the program takes to run. It
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
Now try the program, first removing the old output file:
TU
Here are some system calls that operate on these low-level file descriptors.
lseek
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
The lseek system call sets the read/write pointer of a file descriptor, fildes. You use it
to set where in the file the next read or write will occur.
The offset parameter is used to specify the position and the whence parameter
or
specifies how the offset is used.
The fstat system call returns status information about the file associated with an open
file descriptor.
The members of the structure, stat, may vary between UNIX systems, but will
include:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
The permissions flags are the same as for the open system call above. File-type flags
include:
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
There are some macros defined to help with determining file types. These include:
or
W
To test that a file doesn't represent a directory and has execute permisson set for the
owner and no other permissions, we can use the test:
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The dup system calls provide a way of duplicating a file descriptor, giving two or
more, different descriptors that access the same file.
The standard I/O library and its header file stdio.h, provide a versatile interface to
low-level I/O system calls.
ld
Three file streams are automatically opened when a program is started. They
are stdin, stdout, and stderr.
or
W
TU
fopen
JN
The fopen library function is the analog of the low level open system call.
fopen opens the file named by the filename parameter and associates a stream with it.
The mode parameter specifies how the file is to be opened. It's one of the following
strings:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
If successful, fopen returns a non-null FILE * pointer.
fread
W
The fread library function is used to read data from a file stream. Data is read into a
data buffer given by ptr from the stream, stream.
fwrite
TU
The fwrite library call has a similar interface to fread. It takes data records from the
specified data buffer and writes them to the output stream.
JN
fclose
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The fclose library function closes the specified stream, causing any unwritten data to
be written.
ld
fflush
or
The fflush library function causes all outpstanding data on a file stream to be written
immediately.
fseek W
The fseek function is the file stream equivalent of the lseek system call. It sets the
TU
position in the stream for the next read or write on that stream.
fgetc, getc, getchar
JN
The fgetc function returns the next byte, as a character, from a file stream. When it
reaches the end of file, it returns EOF.
The getc function is equivalent to fgetc, except that you can implement it as a macro.
The getchar function is equivalent to getc(stdin) and reads the next character from
the standard input.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
fputc, putc, putchar
ld
The fputc function writes a character to an output file stream. It returns the value it
has written, or EOF on failure.
or
The function putc is quivalent to fputc, but you may implement it as a macro.
The printf family of functions format and output a variable number of arguments of
different types.
JNTU World Page 137
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Ordinary characters are passed unchanged into the output. Conversion specifiers
cause printf to fetch and format additional argumetns passed as parameters. They are
start with a %.
For example
ld
which produces, on the standard output:
or
Here are some of the most commonly used conversion specifiers:
W
TU
This produces:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
The printf function returns an integer, the number of characters written.
scanf, fscanf and sscanf
W
\
TU
The scanf family of functions work in a similar way to the printf group, except that
thye read items from a stream and place vlaues into variables.
The format string for scanf and friends contains both ordinary characters and
conversion specifiers.
The call to scanf will succeed and place 1234 into the variable num given either if the
following inputs.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Given the input line,
W
this call to scanf will correctly scan four items:
TU
In general, scanf and friends are not highly regarded, for three reasons:
JN
Other library functions use either stream paramters or the standard streams stdin,
stdout, stderr:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
You can use the file stream functions to re-implement the file copy program, by using
library functions.
W
Try It Out - Another File Copy Program
This program does the character-by-character copy is accomplished using calls to the
functions referenced in stdio.h.
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
$ time copy_stdio
1.69user 0.78system 0:03.70elapsed 66%CPU
This time, the program runs in 3.7 seconds.
Stream Errors
To indicate an error, many of the stdio library functions return out of range values,
ld
such as null pointers or the constant EOF.
or
W
You can also interrogate the state of a file stream to determine whether an error has
occurred, or the end of file has been reached.
TU
The ferror function tests the error indicator for a stream and returns non-zero if its
set, zero otherwise.
JN
The feof function tests the end-of-file indicator within a stream and returns non-zero if
it is set zero otherwise.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The clearerr function clears the end-of-file and error indicators for the stream to
which stream points.
ld
Streams and File Descriptors
You can mix low-level input and output operations with higher level stream
or
operations, but this is generally unwise.
W
File and Directory Maintenance
The standard libraries and system calls provide complete control over the creation and
TU
maintenance of files and directories.
chmod
You can change the permissions on a file or directory using the chmod system call.
Tis forms the basis of the chmod shell program.
JN
chown
A superuser can change the owner of a file using the chown system call.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
We can remove a file using unlink.
or
The unlink system call edcrements the link count on a file.
W
The link system call cretes a new link to an existing file.
We can create and remove directories using the mkdir and rmdir system calls.
TU
The mkdir system call makes a new directory with path as its name.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
A program can determine its current working directory by calling the getcwd library
function.
ld
or
The getcwd function writes the name of the current directory into the given
buffer, buf.
Scanning Directories
W
The directory functions are declared in a header file, dirent.h. They use a
structure, DIR, as a basis for directory manipulation.
opendir
JN
readdir
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The readdir function returns a pointer to a structure detailing the next directory entry
ld
in the directory stream dirp.
The dirent structure containing directory entry details included the following entries:
or
telldir
W
The telldir function returns a value that records the current position in a directory
TU
stream.
seekdir
JN
The seekdir function sets the directory entry pointer in the directory stream given
by dirp.
closedir
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The closedir function closes a directory stream and frees up the resources associated
ld
with it.
Try It Out - A Directory Scanning Program
1. The printdir, prints out the current directory. It will recurse for subdirectories.
or
W
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
The program produces output like this (edited for brevity):
or
W
TU
JN
How It Works
After some initial error checking, using opendir, to see that the directory
exists, printdir makes a call to chdir to the directory specified. While the entries
returned by readdir aren't null, the program checks to see whether the entry is a
directory. If it isn't, it prints the file entry with indentation depth.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Errors
W
You can run it using the command:
System calls and functions can fail. When they do, they indicate the reason for their
TU
failure by setting the value of the external varaible errno.
The values and meanings of the errors are listed in the header file errno.h. They
include:
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
There are a couple of useful functions for reporting errors when they
occur: strerror and perror.
TU
The strerror function maps an error number into a string describing the type of error
that has occurred.
JN
The perror function also maps the current error, as reported in errno, into a string
and prints it on the standard error stream.
It's preceded by the message given in the string s (if not null), followed by a colon
and a space. For example:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
Advanced Topics
fcntl
The fcntl system call provides further ways to manipulate low level file descriptors.
or
W
It can perform miscellaneous operations on open file descriptors.
The call,
TU
returns a new file descriptor with a numerical value equal to or greater than the
integer newfd.
The call,
JN
The call,
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The calls,
respectively get and set the file status flags and access modes.
ld
mmap
The mmap function creates a pointer to a region of memory associated with the
contents of the file accessed through an open file descriptor.
or
W
You can use the addr parameter to request a particular memory address.
The prot parameter is used to set access permissions for the memory segment. This is
a bitwise OR of the following constant values.
TU
The flags parameter controls how changes made to the segment by the program are
reflected elsewhere.
JN
The msync function causes the changes in part or all of the memory segment to be
written back to (or read from) the mapped file.
JNTU World Page 153
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The part of the segment to be updated is given by the passed start address, addr, and
length, len. The flags parameter controls how the update should be performed.
ld
or
The munmap function releases the memory segment.
Here is the definition of the RECORD structure and the create NRECORDS versions
each recording their number.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
TU
2. We now change the integer value of record 43 to 143, and write this to the 43rd
record's string:
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
3. We now map the records into memory and access the 43rd record in order to
change the integer to 243 (and update the record string), again using memory
mapping:
ld
or
Summary
W
This chapter showed how LINUX provides direct access to files and devices..
Chapter Outline
Processes and Signals
What is a Process
Process Structure
The Process Table
JN
Viewing Processes
System Processes
Process Scheduling
Starting New Processes
Waiting for a Process
Zombie Processes
Input and Output Redirection
Threads
Signals
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Sending Signals
Signal Sets
Summary
Lecture Notes
Processes and Signals
ld
Processes and signals form a fundamental part of the UNIX operating environment,
controlling almost all activities performed by a UNIX computer system.
or
Here are some of the things you need to understand.
W
What is a Process?
The X/Open Specification defines a process as an address space and single thread of
TU
control that executes within that address space and its required system resources.
Process Structure
Here is how a couple of processes might be arranged within the operationg system.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Each process is allocated a unique number, a process identifier, or PID.
W
The program code that will be executed by the grep command is stored in a disk file.
Viewing Processes
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
The PID column gives the PIDs, the TTY column shows which terminal started the
process, the STAT column shows the current status, TIME gives the CPU time used
or
so far and the COMMAND column shows the command used to start the process.
W
The initial login was performed on virtual console number one (v01). The shell is
running bash. Its status is s, which means sleeping. Thiis is because it's waiting for
the X Windows sytem to finish.
TU
X Windows was started by the command startx. It won't finished until we exit from
X. It too is sleeping.
The fvwm is a window manager for X, allowing other programs to be started and
JN
This process represents a window in the X Windows system. The shell, bash, is
running in the new window. The window is running on a new pseudo terminal
(/dev/ptyp0) abbreviated pp0.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
This is the EMACS editor session started from the shell mentioned above. It uses the
pseudo terminal.
ld
This is a clock program started by the window manager. It's in the middle of a one-
minute wait between updates of the clock hands.
or
System Processes
Let's look at some other processes running on this Linux system. The output has been
abbreviated for clarity:
W
TU
In general, each process is started by another, known as its parent process. A process
so started is known as a child process.
When UNIX starts, it runs a single program, the prime ancestror and process number
one: init.
One such example is the login procedure init starts the getty program once for each
terminal that we can use to long in.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Process Scheduling
ld
One further ps output example is the entry for the ps command itself:
or
This indicates that process 192 is in a run state (R) and is executing the command ps-
ax.
We can set the process priority using nice and adjust it using renice, which reduce the
priority of a process by 10. High priority jobs have negative values.
W
Using the ps -l (forlong output), we can view the priority of processes. The value we
are interested in is shown in the NI (nice) column:
TU
Here we can see that the oclock program is running with a default nice value. If it had
been stated with the command,
We can change the priority of a ruinning process by using the renice command,
JN
So that now the clock program will be scheduled to run less often. We can see the
modified nice value with the ps again:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
Notice that the status column now also contains N, to indicate that the nice value has
changed from the default.
ld
Starting New Processes
We can cause a program to run from inside another program and thereby create a new
process by using the system. library function.
or
complete.
W
The system function runs the command passed to it as string and waits for it to
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
2. When we compile and run this program, system.c, we get the following:
W
TU
We could put the task in the background, by changing the function call to the
following:
JN
Now, when we compile and run this version of the program, we get:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
How It Works
or
In the first example, the program calls system with the string "ps -ax", which
executes the ps program. Our program returns from the call to system when
the ps command is finished.
In the second example, the call to system returns as soon as the shell command
W
finishes. The shell returns as soon as the ps program is started, just as would happen if
we had typed,
at a shell prompt.
TU
Replacing a Process Image
There is a whole family of related functions grouped under the exec heading. They
differ in the way that they start processes and present program arguments.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The exec family of functions replace the current process with another created
according to the arguments given.
If we wish to use an exec function to start the ps program as in our previous examples,
we have the following choices:
ld
or
W
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Now, when we run this program, pexec.c, we get the usual ps output, but no Done.
message at all.
Note also that there is no reference to a process called pexec in the output:
W
TU
How It Works
The program prints its first message and then calls execlp, which searches the
directories given by the PATH environment variable for a program called ps.
It then executes this program in place of our pexec program, starting it as if we had
given the shell command:
JN
To use processes to perform more than one function at a time, we need to create an
entirely separate process from within a program.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
We can create a new process by calling fork. This system call duplicates the current
process.
Combined with exec, fork is all we need to create new processes to do our bidding.
ld
The fork system call creates a new child process, identical to the calling process
or
except that the new process has a unique process ID and has the calling process as its
parent PID.
W
TU
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
TU
JN
This program runs as two process. A child prints a message five times. The parent
prints a message only three times.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
How It Works
or
When the call to fork is made, this program divides into two separate processes.
We can arrange for the parent process to wait until the child finishes before continuing
by calling wait.
W
TU
The wait system call causes a parent process to pause until one of its child processes
dies or is stopped.
We can interrogate the status information using macros defined in sys/wait.h. These
include:
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
Try It Out - wait
1. Let's modify our program slightly so we can wait for and examine the child process
exit status. Call the new program wait.c.
W
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
TU
JN
2. This section of the program waits for the child process to finish:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
When we run this program, we see the parent wait for the child. The output isn't
W
confused and the exit code is reported as expected.
TU
JN
How It Works
The parent process uses the wait system call to suspend its own execution until status
information becomes available for a child process.
Zombie Processes
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
When a child process terminates, an association with its parent survives until the
parent in turn either terminates normally or calls wait.
ld
fork2.c is jsut the same as fork.c, except that the number of messages printed by the
child and paent porcesses is reversed.
or
W
TU
How It Works
If we run the above program with fork2 & and then call the ps program after the child
has finished but before the parent has finished, we'll see a line like this:
JN
There's another system call that you can use to wail for child processes. It's
called waitpid and youu can use it to wait for a specific process to terminate.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
If we want to have a parent process regularly check whether a specific child process
ld
had terminated, we could use the call,
or
which will return zero if the child has not terminated or stopped or child_pid if it has.
1. Here's a very simple filter program, upper.c, to convert all characters to uppercase:
TU
JN
When we run this program, it reads our input and converts it:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
We can, of course, use it to convert a file to uppercase by using the shell redirection:
$ cat file.txt
this is the file, file.txt, it is all lower case.
or
$ upper < file.txt
THIS IS THE FILE, FILE.TXT, IT IS ALL LOWER CASE.
2. What if we want to use this filter fromwithin another program? This
code, useupper.c, accepts a file name as an argument and will respond with an error if
called incorrectly:
W
TU
3. The done, we reopen the standard input, again checking for any errors as we do so,
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
4. don't forget that execl replaces the current process; provided there is no error, the
or
remaining lines are not executed:
How It Works
W
when we run this program, we can give it a file to convert to uppercase. The job is
done by the program upper. The program is executed by:
TU
Because open file descriptors are preserved across the call to execl,
the upper program runs exactly as it would have under the shell command:
JN
Threads
UNIX processes can cooperate; they can send each other messages and they can
interrupt one another.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
There is a class of process known as a thread which are distinct from processes in
that they are separate execution streams within a single process.
Signals
ld
Signal names are defined in the header file signal.h. They all begin with SIG and
include:
or
W
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
If the shell and terminal driver are configured normally, typing the interrupt character
(Ctrl-C) at the keyboard will result in the SIGINT signal being sent to the foreground
process. This will cause the program to terminate.
W
We can handle signals using the signal library function.
TU
The signal function itself returns a function of the same type, which is the previous
value of the function set up to handle this signal, or one of these tow special values:
JN
1. We'll start by writing the function which reacts to the signal which is passed in the
parameter sig. Let's call it ouch:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
2. The main function has to intercept the SIGINT signal generated when we type
Ctrl-C.
or
For the rest of the time, it just sits in an infinite loop, printing a message once a
second:
W
TU
3. While the program is running, typing Ctrl-C causes it to react and then continue.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
How It Works
Sending Signals
W
The program arranges for the function ouch to be called when we type Ctrl-C, which
A process may send a signal to another process, including itself, by calling kill.
JN
The alarm function call can be used by a process to schedule a SIGALRM signal at
some time in the future.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
1. In alarm.c, the first function, ding, simulates an alarm clock:
or
W
2. In main, we tell the child process to wait for five seconds before sending
a SIGALRM signal to its parent:
TU
JN
3. The parent process arranges to catch SIGALRM with a call to signal and then
waits for the inevitable.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
When we run this program, it pauses for five seconds while it waits for the simulated
alarm clock.
or
W
This program introduces a new function, pause, which simply causes the program to
suspend execution until a signal occurs.
TU
How It Works
JN
The alarm clock simulation program starts a new process via fork. This child process
sleeps for five seconds and then sends a SIGALRM to its parent.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The sigaction structure, used to define the actions to be taken on receipt of the signal
ld
specified by sig, is defined in signal.h and has at least the following members:
or
Try It Out - sigaction
Make the changes shown below so that SIGINT is intercepted by sigaction. Call the
new program ctrlc2.c. W
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
TU
Running the program, we get a message when we type Ctrl-C because SIGINT is
handled repeated;y by sigaction.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
How It Works
W
The program calls sigaction instead of signal to set the signal handler for Ctrl-C
(SIGINT) to the function ouch.
TU
Signal Sets
The header file signal.h defines the type sigset_t and functions used to manipulate
sets of signals.
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
The process signal mask is set or examined by calling the function sigprocmask.
ld
or
sigprocmask can change the process signal mask in a number of ways according to
the how argument.
A program can determine which of its blocked signals ar pending by calling the
function sigpending.
JN
A process can suspend execution until the delivery of one of a set of signals by
calling sigsuspend.
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
sigaction Flags
ld
The sa_flags field of the sigaction structure used in sigaction may contain the
following values to modify signal behavior
or
W
Functions that are safe to call inside a signal handler, those guaranteed by the X/Open
specification either to be re-entrant or not to raise signals themselves include:
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
TU
Here we list the signals that UNIX programs typically need to get involved with,
including the default behaviors:
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
or
W
The default action signals is abnormal termination of the process.
TU
JN
JNTU World
www.alljntuworld.in JNTU World
Linux Programming
ld
A process is stopped by default on receipt of one of the above signals.
or
W
SIGCONT restarts a stopped process and is ignored if received by a process which is
not stopped.
TU
Summary
We have seen how processes are a fundamental part of the LINUX operation system.
JNTU World