Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
UNIX PROGRAMMING
4th Semester BCA
Chapter-1
Operating system:
Operating system is the software that manages the computer’s hardware and
provides convenient and safe environment for running programs. It acts as an interface
between programs and the hardware resources.
It is loaded into memory when a computer is booted and remains active as long as
machine is up. After any program has completed execution, the operating system cleans up the
memory and registers and makes them available for the next program.
Like DOS and WINDOWS, there is another operating system called UNIX. It
arrived earlier than other two. UNIX is a gient operating system, and is way ahead of them in sheer
power. It has practically everything an operating system should have, and several features which
other operating systems never had.
The UNIX was pioneered by Ken Thompson and Dennis Ritchie at AT & T Bell Labs in
1960’s.
The design of this operating system was to create an environment that promoted efficient
program development.
The origin of UNIX operating system was MULTICS, it is a time sharing operating system.
The Unix operating system found its beginnings in MULTICS, which stands for Multiplexed
Operating and Computing System. The MULTICS project began in the mid 1960s as a joint
effort by General Electric, Massachusetts Institute for Technology and Bell Laboratories. In 1969
Bell Laboratories pulled out of the project.
One of Bell Laboratories people involved in the project was Ken Thompson. He liked the
potential MULTICS had, but felt it was too complex and that the same thing could be done in
simpler way. In 1969 he wrote the first version of Unix, called UNICS. UNICS stood for
Uniplexed Operating and Computing System. Although the operating system has changed, the
name stuck and was eventually shortened to Unix.
Ken Thompson teamed up with Dennis Ritchie, who wrote the first C compiler. In 1973 they
rewrote the Unix kernel in C. The following year a version of Unix known as the Fifth Edition
was first licensed to universities. The Seventh Edition, released in 1978, served as a dividing
point for two divergent lines of Unix development. These two branches are known as SVR4
(System V) and BSD (Berkeley software distribution)
One of the biggest reasons for using UNIX is networking capability. With other operating
systems, additional software must be purchased for networking. With UNIX, networking
capability is simply part of the operating system. UNIX is ideal for such things as worldwide
e-mail and connecting to the Internet.
Knowing Machine
Unlike DOS and Windows, UNIX can be used by several users concurrently. If you have access
to such a multiuser system, then in all probability yo will be sitting with just a terminal or monitor
and a keyboard.
Things are different, however when you are the sole user of the system. This could happen if
you work on a desktop machine that has its own CPU, RAM, hard disk, floppy and CD-ROM
drives, printer and controllers of these devices. If you own machine you are directly responsible
for its start’s up, shut down and maintenance. If you lose a file your job to get it from a back up.
Because the system can be used by many users, some one has to be given charge of
administration of the system. This person is known as system administrator, and he is the person
who will grant you authority to use the system. He opens an account with a name for our use, and
gives you a secret code that you have to enter when the system prompts you for it. If you are
running UNIX on your desktop, then remember that you are the administrator of the machine.
3
Unix Programming Vidyavahini First Grade College, Tumkur.
The system shows the $ prompt, with the cursor constantly blinking beside it. This is a typical
UNIX prompt, and many UNIX systems use the $ as the default prompt setting. For some users
you might see the % instead of the $, and the system administrator will use the prompt of #.
• It is case sensitive.
• It has multitasking capability.
• It supports for server or host system.
Questions:
Chapter-2
UNIX Architecture and Command usage
UNIX Architecture:
UNIX is a powerful system. Before we examine the features of this, we need to understand its
software architecture. UNIX components are
• Hardware
• Kernel
• Shell
• Application programs
5
Unix Programming Vidyavahini First Grade College, Tumkur.
Kernel: kernel is the core of the unix operating system. It is loaded into memory when the system
is booted. Kernel directly interacts with the hardware. But it cannot directly interact with the user.
Kernel controls all control resources. Itallocates time and memory for the programs and it will
handles file management system etc. The kernel functions are shown in below
Device drivers
Shell: Shell is an interface between user and the kernel. Shell is known as Command
Interpreter.
Why means suppose we are enter one command at the user prompt at the time kernel
does not interact directly with user. So the Shell will be acivate and take that command searches
code for that. If it succeed in searching then it sends a request to the kernel through system calls
then the kernel will execute that command. This is the purpose shell is known as command
interpreter.
Ex: $ rm myfile
In the above example rm is the command for removing a file. Myfile is the name of the file.
Shell will be searches for the code of rm command. If it suceed that one then kernel will execute
this command. The file myfile will be removed.
Application Programs:
Process
Memory
Department
Dep of BCA
artment of BCA management PagePage
6
management
kernel
File
Unix Programming Vidyavahini First Grade College, Tumkur.
• User mode
• Kernel mode Hardware
7
Unix
Programming Vidyavahini First Grade College, Tumkur.
information.
In general:
$ command name -option(s) arguments
Unix comamnd can have multiple options and arguments.
Here command name and the option seperated by space and option and arguments are also seperated
by space. But hyphen and option are not seperated by space.
• Multiuser Ability
• Mutitasking Ability
• Security
• Communication
• Hierachical file system
• Machine independence
Multiuser Ability:
Unix is a Multiuser operating system. Means one computer resources like hard disk,
memory, printer etc are accessible by many users. That is many users can share the same computer
resources.
Multitasking Ability:
It is the ability of carrying more than one job at a time. Means a single user can run
multiple tasks concurrently. For example user edit a file, print another one on the printer, send mail
to a friend and browse also all without leaving any of the applications.
In a multitasking environment, a user sees one job running in the foreground, the rest run in
the background.
Security:
File level: In this level every user give the permission to the files like read, write and execute. These
permissions can be changed by the user.
Text level: In this we were used encryption tecnique by using crypt command. By using this we
are converting readable format data into unreadable format. If some one succeeds opening our file
the contents of that file will be safe.
Unix system uses a hierachical file structure to store the information. This structure has
maximum flexibility and easy to understand and easy way to maintain.
Machine Independence:
The unix system hides the machine architecture from the user. It will be easier to write
the applications. Those are run on another machines.
General Commands
The cal command with out take any argument it will display present month of the calender. But if
it takes any arguments as month and the year then it will display that specific calender only.
Syntax: $ cal
Calender command canot take any arguments it will display present month of the calender.
Ex: $ echo
Both printf and echo are used same escape sequences Here
Ex3: $ printf “the value of 255 is %o in octal and %x in hexa decimal” Output:
tput is the command which is used to repositioning the cursor and also set background color and
foreground colors. Text will be bold and rebold etc.
In the above example we were used the arguments of cup and 10 and 20.
Using this text will be underlined. To remove that underline rmso is used.
Using this we can set background color. Color cod is numbers or alphabets or alphanumeric.
Using this we can set foreground(text) color. Color cod is numbers or alphabets or alphanumeric
bc
• Compared to bc, xcalc is quite easy to use and it is user friendly, it is graphical
calculatorand visible by user.
• bc command less friendly but extreamly powerful command to perform accurate
caluculations.
Syntax: $ bc
Syntax: $ xcalc
Syntax: $passwd
Conditions:
• It can be not too similar to the old password.
• It must be at least 6 characters. It must not be based on dictionary word.
Option purpose
Using this command display the details of active users, time and also process id etc.
Syntax: $ who
In this command along with who command two arguments are there they are am and i. both are
predefined arguments. Syntax: $who am i
It will display only one user who has presently work on the system.
In Unix even terminals are teated as files. This command is used to display the details about terminals.
Syntax: $ tty
This syntax will display the total information about the calendar command.
Questions:
Chapter-3
Unix looks everything treated as a file and any Unix system has thousands of files. Files grow
rapidly, and they are not organized properly, you will find it difficult to locate them. Unix file
system permits to create folders to store files. These folders are known as directories. The File
(Types of files)
A file is container for storing information. we can treat simply file is a sequence of characters.
• Ordinary files
• Directory files
• Special or device files
Ordinary files:
These are also known as “regular files”. It is the most common type of the file. All
programs we write belongs to this category.
• Text file
• Binary file
A Text file contains only printable characters. The characteristic feature of text files is that the data
inside them are divided into groups of lines, with each line terminated by the new line character.
A Binary file contains both printable and unprintable characters that covers entire ASCII range (0 to
255). Most Unix commands are binary files.
To identify this ordinary file the first character is hyphen symbol (-).
Directory files:
This is a special type of a file in Unix, which only contains a list of files and directories
also.
We cannot work with these directories directly. A directory file contains 2 fields for each file.
they are name of the file and identification number (inode number). This inode is an unique number
to each file and directory.
When an ordinary is created or removed, its corresponding directory file is automatically updated
by the kernel.
Device files:
This type of files are also known as special files. This includes printers, tapes, floppy, CD-
ROM etc. Almost every device has a special file in Unix.
If we want to see those special files or device files then we were use two special directories those are
/dev or /etc.
Types of users
The system administrator is primarily responsible for the operation on the system and also creates
different users of the file.
File owner:
Every file has its owner, he was the person who creates the file. The owner of a file can perform
any type of operation on that file like add, delete etc.
The owner has full control capacity to the accessing of the file at any time.
It is represented by the letter ‘U’.
Group owner:
Suppose we are not the user of owner, the shell will check the member of the group owner.
Whether you are a member of the group or not.
Others:
Users who are neither file owner nor the meber of group that category is known as others.
Types of permissions
• Read (r)
• Write (w)
• Execute (x)
Read:
A user who has read permission for a file can look at the contents of that file.
A user who has read permission for a directory can find out what are the files under that directory.
Read permission is the basic permission of each file and directory.
It is represented by the letter “r” and it is having the permission number “4”.
Write:
A user who has write permission for a file or directory can change the contents or data in file
or directory. In this the user can create a new files and delete and also any type of the
modifications done on them.
It is represented by the letter “w” and it is having the permission number “2”.
Execute:
A user who has execute permission for a file can use that filename as a unix command.
A user who has execute permission for a directory can use that directory name under the root directory.
The above mentioned those are types of files, types of users and types of permissions can be
represented as below. It can be obtained by using “ls” command
- rwx r-- r-- 1 aaa user 1024 month &time file or directory name
U G O owner
directory file
Creating file:
Cat command is used to create a file by using > (redirection) operator. But using this
command we can create only one file at a time.
Using cat command we can append or add content to the existing file. For this purpose
we use >> symbol.
In the above example we are adding some more content to the existing file aaa.
$ cat aaa
By using this command we can create multiple files at a time. But those files are empty. Means using
touch command we cannot insert data into file. For that purpose we will use one editor like emacs, vi
etc.
Using the above example we can create 4 files at a time. But we can not enter data into those files.
By using this command we can also change the accessing time of the given file.
Source file is already created by user. But destination file will create when we are used cp command.
This syntax requires minimum 2 files. In this both files are appeared in our current directory.
In the above example we can copy the information from aaa to bbb.
Using the above syntax we can copy 3 files contents to one directory.
Using this command we can remove file(s) from current directory. By using this we can remove more
than one file at a time.
Syntax: $ rm filename
Syntax: $ rm *
By using this syntax we can remove all files in our current directory.
Syntax: $ rm a*
By using this syntax we can remove all files those files are having the starting letter “a”.
This command is used to display all files and directories in our current directory.
Syntax: $ ls
By using this syntax means ls command it cannot take any arguments and the options it will display
list of files and directories.
Option purpose
-l it display long format of files and directories. -r it display reversed order of file
By using this command we can display the number of lines, number of words and number of characters
in a particular file.
• If wc command cannot take any option it will display number of words, number of
characters and number of lines in a particular file by using the below syntax. Syntax: $
wc filename
Sometimes larger files are impossible to store an editor at that time we can split up those files
automatically kernel created files like xaa, xab, xac….xaz etc.
These are the files kernel created files and these files we can store splitted data.
In the above example split command splits the 3 lines of information to store kernel files in vvfgc
file.
The more command is used to reads the file and display output one page at a time.
cmp command compares two files given as arguments byte by byte. The command does not display
any message, if the files are identical.
The comm command has without take any options it will display 3 column output.
Option purpose
it
diff uses specials and instructions to indicate the changes that are required to make two files identical.
Ex: 4 d 5 it means delete the line 4 from first file and 5 th line in second file.
2 c 4 it means changes the line 2 in first line and 4th line in second file.
0 a 1,2 it means appending two lines after zero, they are added in the second file.
File Compression
Compression of data is when you take a regular size of a file and reduce the amount of disk space
it consumes. Then we need compression application.
When one file can zipped by using the gzip command we cannot open that file, at the time we use
gunzip command.
The UNIX filesystem is laid out as a hierarchical tree structure which is anchored at a special top-level
directory known as the root (designated by a slash '/').
Because of the tree structure, a directory can have many child directories, but only one parent directory.
To specify a location in the directory hierarchy, we must specify a path through the tree.
The path to a location can be defined by an absolute path from the root /, or as a relative path
from the current working directory. To specify a path, each directory along the route from the
source to the destination must be included in the path, with each directory in the sequence being
separated by a slash. To help with the specification of relative paths, UNIX provides the
shorthand "." for the current directory and ".." for the parent directory. For example, the absolute
path to the directory "play" is /home/will/play, while the relative path to this directory from
"zeb" is ../will/play.
/home or User home directories containing personal file space for each user. Each
/homes directory is named after the login of the user.
Directory Commands
Using this commnad creates a subdirectory in the current working directory. You can only create
subdirectories in a directory if you have write permission on that directory.
Syntax: $ cd path
Using this command changes your current working directory to path (which can be an absolute or
a relative path). One of the most common relative paths to use is '..' (i.e. the parent directory of
the current directory).
$ cd dirname
resets your current working directory to your home directory (useful if you get lost). If you change
into a directory and you subsequently want to return to your original directory, use
$ cd -
pwd displays the full absolute path to the your current location in the filesystem. So
Syntax: $ pwd
$ pwd
/usr/bin
5. mv (move/rename)
mv is used to rename files/directories and/or move them from one directory into another.
Exactly one source and one destination must be specified:
If destination is an existing directory, the new name for source (whether it be a file or a directory)
will be destination/source. If source and destination are both files, source is renamed destination.
if destination is an existing file it will be destroyed and overwritten by source (you can use the -i
option if you would like to be asked for confirmation before a file is overwritten in this way).
A wildcard is a character that can be used as a substitute for any of a class of characters in a search,
there by greatly increasing the flexibility and efficiency of searches.
Wildcards are also used in regular expressions and programming languages. Regular expressions
are a pattern matching system that uses strings (i.e., sequences of characters) constructed according
to pre-defined syntax rules to find desired strings in text.
In those first three characters are matching characters. { } this is expanding character.
It will display the all files and directories in current directory, if it is match.
Syntax: ls *
Syntax: ls a*
It will display the all files in a current directory, whose files are starting with the letter “a”.
Syntax: ls *.sh
The question mark (?) is used as a wildcard character in shell commands to represent
exactly one character, which can be any single character. Thus, two question marks in succession
would represent any two characters in succession, and three question marks in succession would
represent any string consisting of three characters.
Syntax: ls ?
It will display the all files in a current directory, whose files are having single character long.
Syntax: file???
It will display the all files in a current directory, whose files are having three character long.
It will display the all files in a current directory, whose files are having five character long.
The third type of wildcard in shell commands is a pair of square brackets, which can
represent any of the characters enclosed in the brackets.
Thus, for example, the following would provide information about all objects in the current directory
that have an x, y and/or z in them:
Syntax: ls *.[xyz]*
And the following would list all files that had an extension that begins with x, y or z:
Boot block:
This represents beginning program for each and every file system. This block contains a program
or software component is loader that is “bootstrap loader”.
Super block:
Inode block:
Each and every file has accessed by a unique number called inode number or inode entry or
inumber. (or)
Inodes are the data structures that contains information about files.
Functions of inode:
• Owner of a file.
• Group owner of a file.
Data block:
This contains all data and programs created by the users that is maintained by data block.
In this disk block size is 1024 bytes. If files contains only one character, an entire data block must
be maintained this single character only.
Internally any file is identified in UNIX by a unique inode number. We can obtained that inode number
with including file names by using the “ ls –i “ option.
Syntax: ls -i filename
In the above example we display the inode number of perticular file “vvfgc”. Here 12345 is the inode
of vvfgc.
Inode number is nothing but an index into the inode table where the information about the files are
stored. Each inode entry in the inode table consists of 13 addresses.
In the above diagram 0 to 12 represent the addresses of the inode numbers. Each inode entry in the
data block must be having the 1KB data. The first 10 addresses (0 to 9) can store 10 KB of data. If
we give more than 10 KB of data then that structure divided into single indirection procedure to
store files.
When the file size is exceeding 266 blocks, the 12th entry comes into play. It points to double indirect
procedure.
The 13th and final entry of the address table points to a triple indirection procedure, when the file size
has exceeded 266 X 266 blocks.
Chapter-4
Filters are the Unix commands which can access some data as input perform manipulation
on it and produces output.
Filter Commands
A regular expression is either some plain text (a word, for example) and/or special characters used
for pattern matching.
The simplest use of grep is to look for a pattern consisting of a single word. It can be used in a
pipe so that only those lines of the input files containing a given string are sent to the standard
output. If you don't give grep a filename to read, it reads its standard input; that's the way all filter
programs work:
$ ls -l | grep "Aug"
-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
There are various options which you can use along with grep command:
Option Description
-v Print all lines that do not match pattern.
-n Print the matched line and its line number.
-l Print only the names of files with matching lines (letter "l") -
c Print only the count of matching lines.
Next, let's use a regular expression that tells grep to find lines with "carol", followed by zero or
more other characters abbreviated in a regular expression as ".*"), then followed by "Aug". Here
we are using -i option to have case insensitive search:
$ ls -l | grep -i "carol.*aug"
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
2. The sort Command
The sort command arranges lines of text alphabetically or numerically. The example below sorts the
lines in the food file
$ sort food
Afghani Cuisine
Bangkok Wok
Big Apple Deli
Isle of Java
Mandalay
Sushi and Sashimi
Sweet Tooth
The sort command arranges lines of text alphabetically by default. There are many options that control
the sorting:
Option Description
-n Sort numerically (example: 10 will sort after 2), ignore blanks and tabs.
-r Reverse the order of sort.
-f Sort upper- and lowercase together.
+x Ignore first x fields when sorting.
More than two commands may be linked up into a pipe. Taking a previous pipe example using grep,
we can further sort the files modified in August by order of size.
The following pipe consists of the commands ls, grep, and sort:
This pipe sorts all files in your directory modified in August by order of size, and prints them to
the terminal screen. The sort option +4n skip four fields (fields are separated by blanks) then
sorts the lines in numeric order.
A long output would normally zip by you on the screen, but if you run text through more or pg as a
filter, the display stops after each screenful of text.
Let's assume that you have a long directory listing. To make it easier to read the sorted listing, pipe
the output through more as follows:
The screen will fill up with one screenful of text consisting of lines sorted by order of file size. At
the bottom of the
screen is the more prompt where you can type a command to move through the sorted text.
When you're done with this screen, you can use any of the commands listed in the discussion of the
more program.
3. Head command
head outputs the first part of files
Syntax: head [options] filename Selected
options:
– -cn : print the first n characters of the file
4. Tail command
tail outputs the last part of files Format:
tail [options] filename
• Selected options:
– -cn : print the last n characters of the file
– -n : print the last n lines the default is 10
• Command:
tail –c5 abc # displays last 5 characters (includes whitespace) tail
abc # displays last 10 lines of abc
• Pipe
ls | tail -15 # displays last 15 lines of file listing head
abc | tail -5 # prints lines 6 through 10 of file abc
5. Uniq Command
Format: uniq [options] filename
sort abc | uniq –c # put abc in order and tell me how many lines are unique
6. Cut command
Examples:
cut -d: -f5 /etc/passwd (print only the 5th field, delimited by colon(:), of the /etc/passwd file) cut
–d” “ –f2 shuffled (print only the 2nd field, delimited by a space, from file shuffled)
cut –c4-8 shuffled (print only the columns 4 through 8 of each line in shuffled.
Example: ls | wc –l
Chapter-5 Process
Management
Process:
When the process starts execution that state is known as born state. In this state program is alive.
• Process id (pid)
• Parent process id (ppid)
Process id:
Each process has uniquely identified by a number is called process id. In shortcut we
represents it as “pid”. It has taking integer values only and its range will be 0 to 30000.
The kernel will assign pid when a new process is created. We can obtain that process id
by using “getpid()” system call.
every process has a parent process and it should have one id that is “ppid”. It will be
obtained by using the syntax int getppid ( ); it will also takes only integer values.
Shell process
When we login to the Unix system a process is immediately setup by the kernel and shell will be
activated. To know the pid of our current shell by using the following syntax.
Syntax: $echo $$
Output: 291
Output: bin/bash
• new state
• ready state
• running state
• sleeping state
• terminated (or) zombie state
New state:
in this state process is created through the fork( ) system call. The fork( ) system call creates
the child processes those are identical to the parent process.
Syntax: $ fork ( )
Ready state:
In this state process is not running, but it is ready for run as soon as the kernel schedules the
process.
Running state:
one process is executed through the exec ( ) system call we can mention the process name and
arguments.
Here * is nothing but meta character. It will show the all information about that process. And arguments
are array of characters.
Sleeping state:
In this state process is in sleeping mode at the time it cannot continued execution because
of some resources are unavailability. It can be obtained by sleep ( ) system call. Syntax: $ sleep
();
Zombie state:
After completion of execution the process will be exit or terminated through the exit ( ) system
call. This is the final state of the process.
Syntax: $ exit ( ) ;
What is spawning?
When one process creates another new process is known as spawning. Here existing process is
called as parent process and newly created process is child process.
It is easy to see your own processes by running the ps (process status) command as follows:
Syntax: $ ps option
$ ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh
18361 ttyp3 00:01:31 abiword
18789 ttyp3 00:00:00 ps
One of the most commonly used flags for ps is the -f ( f for full) option, which provides more
information as shown in the following example:
$ ps -f
Column Description
UID User ID that this process belongs to (the person running it).
PID Process ID.
PPID Parent process ID (the ID of the process that started it).
C CPU utilization of process.
STIME Process start time.
TTY Terminal type associated with the process
TIME CPU time taken by the process.
CMD The command that started this process.
There are other options which can be used along with ps command:
Option Description
-a Shows information about all users
-x Shows information about processes without terminals.
-u Shows additional information like -f option.
-e Display extended information.
Stopping Processes(kill command)
Ending a process can be done in several different ways. Often, from a console-based command,
sending a CTRL + C keystroke (the default interrupt character) will exit the command. This works
when process is running in foreground mode.
If a process is running in background mode then first you would need to get its Job ID using ps
command and after that you can use kill command to kill the process as follows:
$ps -f
UID PID PPID C STIME TTY TIME CMD
amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh amrood
6892 3662 4 10:51:50 pts/6 0:00 ps -f
$kill 6738
Terminated
Here kill command would terminate first_one process. If a process ignores a regular kill command,
you can use kill -9 followed by the process ID as follows:
$kill -9 6738
Terminated
Starting a Process
When you start a process (run a command), there are two ways you can run it:
• Foreground Processes
• Background Processes
Foreground Processes:
By default, every process that you start runs in the foreground. It gets its input from the keyboard and
sends its output to the screen.
You can see this happen with the ls command. If I want to list all the files in my current directory,
I can use the following command:
$ls ch*.doc
This would display all the files whose name start with ch and ends with .doc:
The process runs in the foreground, the output is directed to my screen, and if the ls command wants
any input (which it does not), it waits for it from the keyboard.
While a program is running in foreground and taking much time, we cannot run any other
commands (start any other processes) because prompt would not be available until program finishes
its processing and comes out.
Background Processes:
A background process runs without being connected to your keyboard. If the background process
requires any keyboard input, it waits.
The advantage of running a process in the background is that you can run other commands; you do
not have to wait until it completes to start another!
The simplest way to start a background process is to add an ampersand ( &) at the end of the command.
This would also display all the files whose name start with ch and ends with .doc:
Here if the ls command wants any input (which it does not), it goes into a stop state until I move it
into the foreground and give it the data from the keyboard.
That first line contains information about the background process - the job number and process ID.
You need to know the job number to manipulate it between background and foreground.
If you press the Enter key now, you see the following:
The first line tells you that the ls command background process finishes successfully. The second is
a prompt for another command.
Daemon Processes:
Daemons are system-related background processes that often run with the permissions of root and
services requests from other processes.
A daemon process has no controlling terminal. It cannot open /dev/tty. If you do a "ps -ef" and look
at the tty field, all daemons will have a? for the tty.
More clearly, a daemon is just a process that runs in the background, usually waiting for something
to happen that it is capable of working with, like a printer daemon is waiting for print commands.
If you have a program which needs to do long processing then it’s worth to make it a daemon and
run it in background.
It is an interactive diagnostic tool that updates frequently and shows information about physical and
virtual memory, CPU usage, load averages, and your busy processes.
Here is simple syntax to run top command and to see the statistics of CPU utilization by different
processes: $top
The at command
The at command executes commands at a given time, using your default shell unless you tell the
command otherwise (see the man page).
The options to at are rather user-friendly, which is demonstrated in the examples below:
The -m option sends mail to the user when the job is done, or explains when a job can't be done.
The command at q lists jobs; perform this command before submitting jobs in order prevent them
from starting at the same time as others. With the atrm command you can remove scheduled jobs
if you change your mind.
For example, jobs are often run at exactly 1 o'clock in the morning (e.g. system indexing to update
a standard locate database), so entering a time of 0100 may easily slow your system down rather
than fire it up. To prevent jobs from running all at the same time, you may also use the batch
command, which queues processes and feeds the work in the queue to the system in an evenly
balanced way, preventing excessive bursts of system resource usage. See the Info pages for more
information.
The cron system is managed by the cron daemon. It gets information about which programs and
when they should run from the system's and users' crontab entries. Only the root user has access to
the system crontabs, while each user should only have access to his own crontabs. On some
systems (some) users may not have access to the cron facility.
At system startup the cron daemon searches /var/spool/cron/ for crontab entries which are
named after accounts in /etc/passwd, it searches /etc/cron.d/ and it searches /etc/crontab,
then uses this information every minute to check if there is something to be done. It executes
commands as the user who owns the crontab file and mails any output of commands to the owner.
Alternative
Some variables are set, and after that there's the actual scheduling, one line per job, starting with 5
time and date fields. The first field contains the minutes (from 0 to 59), the second defines the
hour of execution (0-23), the third is day of the month (1-31), then the number of the month (112),
the last is day of the week (0-7, both 0 and 7 are Sunday). An asterisk in these fields represents
the total acceptable range for the field. Lists are allowed; to execute a job from Monday to Friday
enter 1-5 in the last field, to execute a job on Monday, Wednesday and Friday enter 1,3,5.
Chapter-6
Shell Programming
The shell provides you with an interface to the UNIX system. It gathers input from you and executes
programs based on that input. When a program finishes executing, it displays that program's output.
A shell is an environment in which we can run our commands, programs, and shell scripts. There
are different flavors of shells, just as there are different flavors of operating systems. Each flavor
of shell has its own set of recognized commands and functions.
Shell Prompt:
The prompt, which is called command prompt, is issued by the shell. While the prompt is displayed, you
can type a command.
The shell reads your input after you press Enter. It determines the command you want executed by
looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs
separate words.
Following is a simple example of date command which displays current date and time:
$date
Shell Types:
1. The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $
character.
2. The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows:
• C shell ( csh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he was at AT&T
Bell Labs in New Jersey.
The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as "the shell".
The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this reason, it is the
shell of choice for writing scripts to use on several different versions of UNIX.
Shell Scripts:
The basic concept of a shell script is a list of commands, which are listed in the order of execution.
A good shell script will have comments, preceded by a pound sign, #, describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing us to go
through massive amounts of data, files to read and store data, and variables to read and store
data, and the script may include functions.
Shell scripts and functions are both interpreted. This means they are not compiled.
Example Script:
Assume we create a test.sh script. Note all the scripts would have .sh extension. Before you add
anything else to your script, you need to alert the system that a shell script is being started. This is
done using the shebang construct. For example:
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne shell. It's called
a shebang because the # symbol is called a hash, and the ! symbol is called a bang.
To create a script containing these commands, you put the shebang line first and then add the commands:
#!/bin/bash
pwd
ls
Shell Comments:
#!/bin/bash
# this is vvfgc
# Copyright (c) vvfgc.com
# Script follows here: pwd
ls
Now you save the above content and make this script executable as follows:
$chmod +x test.sh
Now you have your shell script ready to be executed as follows: $./test.sh
The shell is, after all, a real programming language, complete with variables, control structures, and
so forth. No matter how complicated a script gets, however, it is still just a list of commands
executed sequentially.
Following script use the read command which takes the input from the keyboard and assigns it as
the value of the variable PERSON and finally prints it on STDOUT.
$./test.sh
What is your name? vvfgc
Hello, vvfgc
Variables
Variable is value that always changes during execution of a program. It is an integral part of shell
programming. They provide the ability to store and manipulate information.
• Environment variables
• User defined variables
Environment variables:
These variables are the part of the system and these are created and maintained by the
syatem itself. These variables always in capital letters only.
Variable meaning
variable_name = variable_value
For example:
NAME = "vvfgc"
Above example defines the variable NAME and assigns it the value "vvfgc". Variables of this type
are called scalar variables. A scalar variable can hold only one value at a time.
The shell enables you to store any value you want in a variable. For example:
VAR1="vvfgc " VAR2=100
To access the value stored in a variable, prefix its name with the dollar sign ( $):
For example, following script would access the value of defined variable NAME and would print it
on STDOUT:
Output: vvfgc
Read-only Variables:
The shell provides a way to mark variables as read-only by using the “read only” command. After
a variable is marked read-only, its value cannot be changed.
For example, following script would give error while trying to change the value of NAME:
Unsetting Variables:
Unsetting or deleting a variable tells the shell to remove the variable from the list of variables that
it tracks. Once you unset a variable, you would not be able to access stored value in the variable.
Following is the syntax to unset a defined variable using the unset command: unset
variable_name
Above command would unset the value of a defined variable. Here is a simple example
NAME="vvfgc" unset
NAME echo $NAME
Above example would not print anything. You cannot use the unset command to unset variables that
are marked readonly.
Read command
The variable used along with the read command need not be preceded by the $ symbol.
Ex: clear echo “enter ur name” read name echo “hello $name”
Hello vvfgc
Expr command
Where ( ` ) this symbol is known as grep symbol. There is always must a space between symbol
and the expr command. Ex: clear echo “enter 2 numbers” read a b
In unix multiplication purpose we use the symbol of “\*” because only * is wild card character.
Operators:
Show Examples
Bourne Shell supports following relational operators which are specific to numeric values. These
operators would not work for string values unless their value is numeric.
For example, following operators would work to check a relation between 10 and 20 as well as in
between "10" and "20" but not in between "ten" and "twenty".
Show Examples
It is very important to note here that all the conditional expressions would be put inside square braces
with one spaces around them, for example [ $a <= $b ] is correct where as [$a <= $b] is incorrect.
Show Examples
Assume a variable file holds an existing file name "test" whose size is 100 bytes and has read, write
and execute permission on:
Show Examples
Operator Description Example
Checks if file is a block special file if yes then
-b file [ -b $file ] is false.
condition becomes true.
Checks if file is a character special file if yes
-c file [ -b $file ] is false.
then condition becomes true.
Check if file is a directory if yes then condition
-d file [ -d $file ] is not true.
becomes true.
Check if file is an ordinary file as opposed to a
-f file directory or special file if yes then condition [ -f $file ] is true. becomes true.
Checks if file has its set group ID (SGID) bit
-g file [ -g $file ] is false.
set if yes then condition becomes true.
Checks if file has its sticky bit set if yes then
-k file [ -k $file ] is false.
condition becomes true.
Checks if file is a named pipe if yes then
-p file [ -p $file ] is false.
condition becomes true.
Checks if file descriptor is open and associated
-t file with a terminal if yes then condition becomes [ -t $file ] is false.
true.
Checks if file has its set user id (SUID) bit set
-u file [ -u $file ] is false.
if yes then condition becomes true.
Checks if file is readable if yes then condition
-r file [ -r $file ] is true.
becomes true.
Control statements
The ability to control the flow of execution of program is known as control statements.
• if-then-fi statement
• if-then-else-fi statement
• if-then-elif-then-else-fi statement case-esac statement if-then-fi statement:
in this first check the condition. That condition is true then only the if block statements will
be executed otherwise the cursor transfer outside the if condition.
Syntax: ex:
if [ condition ] if [ $a –gt 18 ]
then then
fi fi
if-then-else-fi statement:
in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the else block statements will be executed.
Syntax: ex:
if [ condition ] if [ $a –gt $b ]
then then
else
fi fi
if-then-elif-then-else-fi statement:
in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the cursor checks the next condition then the second condition will be
true then inside that statements will be executed and so on. If any conditions were not true then the
else block statements will be executed.
Syntax: ex:
then then
then then
else else
fi fi
Case-esac statement:
[match1] ) statements ; ;
[match2] statements ; ;
[match3] statements ; ;
: :
: :
*) statements ; ;
esac
read ch
case $ch in
esac
• While loop
• Until loop
• For loop
While loop:
This is the pretested loop or entry controlled loop. In this first check the condition, if that
condition was true then control enter inside the loop otherwise control transferred outside the loop.
Syntax: ex:
do do
done
until loop:
This is also pretested loop or entry controlled loop. In this first check the condition, if that
condition was false then control enter inside the loop otherwise control transferred outside the loop.
Syntax: ex:
do do
i =` expr $i + 1 `
done
for loop:
This is a fixed execution loop. This loop is allow to execute list of statements certain period of
time.
Syntax:
do
statements
done
ex: for i in 1 2 3
45
do
echo $i
Sample programs
clear
expr $even + 2 `
done
odd=1
le $limit ] do
echo “$odd”
done
a=1 b=3
while [
$a –le
10 ] do
echo
“$a,\c”
echo
‘$b,\c”
a=`
expr $a
+1`
b=`
expr $b
+1`
done
p=` expr $n \* $i `
echo “$n * $i = $p” i=`
expr $i + 1 ` done
i=1
f=1
while [ $i –le $n ]
do
f=` expr $f \* $i `
i=` expr $i + 1 `
done
echo “factorial of $n is $f”
else
echo “enter a positive number”
fi
7. #script to check whether the given year is leap year or not.
fi
esac
i=` expr $i + 1 `
done echo “string is
$str”
10.# This script displays the date, time, username and current
directory.
11.#!/bin/bash
x=10 #NOT x = 10 no spaces X=20
#variables are case sensitive
$y= #NULL variable
echo "x = $x" echo
"X = $X" echo "y
= $y"
Chapter-7
The users can easily send mails, data, images, pictures etc information to the another users through
the server. Sometimes there are thousands of users sharing the system resources. At that time these
communication commands can be used.
• Write command
• Wall command
• Mesg command
• Finger command
• Mail command
• News command Write command:
Using this command we can send a message to another one user only. If the recipient has take the
permission to receive the messages. Otherwise he cannot receive any messages from other users.
Syntax
If you wish to talk to someone on your own machine, then person is just the person's Person
login name. If you wish to talk to a user on another host, then person is of the form 'user@host'.
If you wish to talk to a user who is logged in more than once, the ttyname argument may
ttyname be used to indicate the appropriate terminal name, where ttyname is of the form 'ttyXX' or
'pts/X'.
Examples
Write vvfgc
Typing the above command would start a talking session with the vvfgc . If you type your name, you
can echo back
If we are return back our prompt press ctrl+d
Mesg command:
This command shows users either interact to receive the messages or not.
Here also recipient must be login otherwise error message will be displayed.
Lets you control if people can use the write command, to send text to you over the screen.
Syntax
$ mesg [n | y]
Examples
mesg
Typing this command by itself will display whether or not the mesg service is enabled. For example,
it may display: "is y", indicating that it is enabled. Typing n or why after the command would
enable or disable this command.
When this command is disabled non-root users will be unable to to send messages to you using message
commands such as talk or write.
Wall command:
Wall sends a message to everybody logged in with their mesg permission set to yes. The
message can be given as an argument to wall, or it can be sent to wall's standard input. When
using the standard input from a terminal, the message should be terminated with the EOF key
(usually Control-D).
Syntax
wall displays the contents of file or, by default, its standard input, on the terminals of all currently
logged in users. The command will cut over 79 character long lines to new lines. Short lines are
white space padded to have 79 characters. The command will always put carriage return and new
line at the end of each line.
Only the super user can write on the terminals of users who have chosen to deny messages or are using
a program which automatically denies messages.
Reading from a file is refused when the invoker is not super user and the program is sued or said.
Examples
Typing the above command from root would broadcast "there is hope" to all other users termial
who are logged into the computer. Below is an example of what each terminal would show after the
wall post.
there is hope
Finger command:
This command displays the information about the system users, who are presently loged
in.
Syntax: $finger
Here * symbol indicates that particular user have set the permission mesg n
Mail command:
Using this command we can send a mesg to all users who are presently login or not.
It can also be used to send messages to other users who have not currently logged in. Syntax: