0% found this document useful (0 votes)
9 views28 pages

Module - 1 - Unix System Programming (BCS515C)

The document outlines the curriculum for the Unix System Programming course at R. L. Jalappa Institute of Technology, detailing the module's objectives, educational outcomes, and key components of the Unix operating system. It covers the architecture of Unix, including the kernel and shell, file and process management, system calls, and various features of Unix such as multitasking and pattern matching. Additionally, it discusses the Unix environment, structure, POSIX standards, and the general command structure used in Unix systems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

Module - 1 - Unix System Programming (BCS515C)

The document outlines the curriculum for the Unix System Programming course at R. L. Jalappa Institute of Technology, detailing the module's objectives, educational outcomes, and key components of the Unix operating system. It covers the architecture of Unix, including the kernel and shell, file and process management, system calls, and various features of Unix such as multitasking and pattern matching. Additionally, it discusses the Unix environment, structure, POSIX standards, and the general command structure used in Unix systems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Sri Devaraj Urs Educational Trust (R.

)
R. L. JALAPPA INSTITUTE OF TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to VTU, Belagavi & Accredited by NAAC “A” Grade)
Kodigehalli, Doddaballapur- 561 203
Department of CS&E (Artificial Intelligence & Machine Learning)

Subject Code: BCS515C


Subject Name: Unix System Programming
Module Number: 01
Name of the Module: Introduction and Unix files
Scheme: 2022
Prepared by: Dr. Manjunatha B N
Associate Professor & HoD
Institute Vision
To be a premier Institution by imparting quality Technical education, Professional Training and Research.

Institute Mission
M1: To provide an outstanding Teaching, Learning and Research environment through Innovative Practices
in Quality Education.
M2: Develop Leaders with high level of Professionalism to have career in the Industry, Zeal for Higher
Education, focus on Entrepreneurial and Societal activities.

Department Vision
To empower the students with knowledge and skills to develop the competency in the field of Artificial
Intelligence and Machine Learning.

Department Mission
M1: To craft the students with Novel and Intellectual skills to capability in the field of Artificial Intelligence
and Machine Learning.
M2: To train the students to have Professional career in the field of AI and ML and zeal for Higher Studies
and Research.

PROGRAMME SPECIFIC OUTCOMES (PSOs)


PSO1: Students will have the ability to understand analyse and demonstrate the knowledge of Human
cognition, Artificial Intelligence, Machine Learning in terms of real world problems to meet the challenges
of future.
PSO2: Students will have the knowledge of software, Hardware, Algorithms, Modelling Networking and
Application Development.
PSO3: Students will have the ability to develop computational knowledge using Innovative tools and
techniques to solve problems in the areas related to Machine learning and Artificial Intelligence.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)


PEO1: Graduates will have Prospective careers in the field of AI and ML.
PEO2: Graduates will have good Leadership Qualities, Self Learning abilities and zeal for higher studies
and Research.
PEO3: Graduates will follow Ethical Practices and exhibit high level of professionalism by participating
and addressing Technical, Business and Environmental challenges.
Module-1 Unix System Programming

Module 1

1. Unix Components/Architecture

1.1 Division of Labor: Kernel and Shell


 UNIX architecture comprises of two major components viz., the shell and the kernel.
 The kernel interacts with the machine’s hardware and the shell interacts with the user.

Figure: The Kernel-Shell Relationship

The kernel
 Is the core of the operating system.
 It is a collection of routines(functions) written in C.
 It is loaded into memory when the system is booted and communicates directly with the
hardware.
 User programs that need to access the hardware use the services of the kernel via use of
system calls and the kernel performs the job on behalf of the user.
 Kernel is also responsible for managing system’s memory, schedules processes, and
decides their priorities.

The Shell
 This acts as an interface between user and the kernel.
 When user types in the terminal , shell interprets the command and calls the program
that user wants. It uses the standard syntax for all commands.
 The shell is represented by

Dept., of CS&E(AI & ML), RLJIT Page 1 Dr. Manjunatha B N


Module-1 Unix System Programming

sh(Bourne shell),csh(C shell), ksh(korn shell) or bash(Bash shell).


Example
How the shell examines and tampers with our input, consider this echo command which
has lots of spaces between the arguments:
Example:
$ echo Sun Solaris
Sun Solaris
 Shell compresses all multiple contiguous spaces in the above command line to a single
one. The echo command then runs with spaces compressed.
The File and Process:

1.2 The File and Process


Files and Directories
 In UNIX, all the data is organized into files.
 All files are organized into directories.
 These directories are organized into a tree-like structure called the file system.

Process:
 A process, which is the name given to a file when it is executed as a program.
 You can say that a process is simply the “time image” of an executable file.
 Like files, processes also belong to a separate hierarchical tree structure.
 UNIX provides the tools that allow us to control process, move them between
foreground and background, and even kill them.

NOTE: “Files have places and Processes have life”.

1.3 The System Calls

 A request for the operating system to do something on behalf of the user's program.
 The system calls are functions used in the kernel itself.
 Unix consisting of thousand commands in the system, they all use a handful of function,
called SYSTEM CALLS, to communicate with the kernel.
 UNIX command writes a file with the write system call without going into the innards
that actually achieve the write operation.
 The same system call can access both a file and a device; the open system call opens
both.
 These system calls are built into the kernel and interaction through them represents an
efficient means of communication with the system.

Dept., of CS&E(AI & ML), RLJIT Page 2 Dr. Manjunatha B N


Module-1 Unix System Programming

2. Features of Unix
The following sections present the major features of this operating system.
1. UNIX: A Multiuser system:
 UNIX is a multiprogramming system, it permits multiple programs to run and
compete for the attention of the CPU.
 This can happen in two ways:
• Multiple users can run separate jobs.
• A single user can also run multiple jobs.

2. UNIX: A Multitasking System:


 UNIX allows a user to run more than one program at a time.
 In fact more than one program can be running in the background while a user
is working foreground.

3. The Building-Block Approach:


 In UNIX we have thousands of command; each of the command does a unique
job. But it also provides an option to the user to combine two commands
together so that a new job is achieved.
Example:
 we can list the contents of the directory by using ls command and count the
words, characters and lines in a file by using wc command. These two
commands can be combined together by using special characters know as
filters.
ls | wc
Combined commands will give the count of number of files in your directory.
Note: | (pipe)

4. The UNIX Toolkit


 The kernel is the one which looks after everything. But the kernel by itself
doesn’t do all that can benefit the user.
 In order to exploit the power of UNIX, we need to use some host of
applications such as general purpose tools, text manipulation tools (filters),
compilers, networking tools, disk fragmentation tools and system
administration tools which comes with every UNIX system. So, UNIX
provides a toolkit for the user benefit.

5. Pattern Matching
 Suppose if we want to list the files which starts with the filename chap then
by using only ls we can’t achieve that. So UNIX provides us options of using
a special character know as a metacharacter.
Example:
ls chap*
chap01
chap02
chap03

Dept., of CS&E(AI & ML), RLJIT Page 3 Dr. Manjunatha B N


Module-1 Unix System Programming

 The * is a special character used by the system to indicate that it can match a
number of filenames.
 UNIX also supports regular expressions, which are framed with the characters
from the metacharacters set.
So, UNIX supports pattern matching concept also.

6. Programming Facility
 The UNIX shell is also a programming language.
 UNIX shell contains all the features, like control structure, loops and
variables, which makes UNIX as a powerful programming language.

7. Documentation
 To know about UNIX in detail there exist many online help facilities like man
command. It is the most important reference for commands and their
configuration files.
 The FAQ(Frequently asked Questions)- a document that addresses common
problems- is also widely available on the Net.

3. The UNIX Environment and UNIX Structure

3.1 The UNIX Environment


 UNIX is a multiuser, multiprocessing, portable operating system designed to facilitate
programming, text processing, communication, and many other tasks that are expected
from an operating system.
 Three different computing environments:
 Stand –alone personal environment
 Time-sharing systems, and
 Client/server systems

 Personal Environment:
 Although originally designed as a multiuser environment, many users are installing UNIX
on their personal computers.
 This trend to personal UNIX system accelerated in the mid -1990’s with the availability of
Linux, a free UNIX system.
 The Apple System X, released in 2001, incorporated UNIX as its kernel.

Dept., of CS&E(AI & ML), RLJIT Page 4 Dr. Manjunatha B N


Module-1 Unix System Programming

 Time-sharing Environment:
 Employees in large companies often work in what is known as a time-sharing environment.

 In a time-sharing environment, all of the computing must be done by the central computer.
 In other words, the central computer has many duties:
 It must control the shared resources
 It must manage the shared data and printing, and
 It must also do the computing.

 Client/Server Environment:

 A client/server computing environment splits the computing function between a central


computer and user’s computers.
 In the client/server environment, the user’s microcomputers or workstations are called the
client.
 The central computer, which may be a powerful microcomputer, a minicomputer, or a
central main-frame system, is known as the server.

3.2 UNIX Structure

Dept., of CS&E(AI & ML), RLJIT Page 5 Dr. Manjunatha B N


Module-1 Unix System Programming

UNIX consists of four major components: the kernel, the shell, a standard set of utilities, and
application programs.

 The Kernel:

 The kernel is the heart of the UNIX system.


 It contains the two most basic parts of the operating system: Process control and resource
management.
 All other components of the system call on the kernel to perform these services for them.

 The Shell:

 The shell is the part of UNIX that is most visible to the user.
 It receives and interprets the commands entered by the user.
 There are two major parts of a shell.
 The first part is the interpreter.
The interpreter reads your commands and works with the kernel to execute them.
 The second part of the shell is a programming capability that allows you to write
a shell(command)script.
 A shell script is a file that contains shell commands that perform a useful function.
It is also known as a shell program.
 There are three standard shells used in UNIX today.
 The Bourne shell, developed by Steve Bourne at the AT&T Labs, is the oldest.
Because it is the oldest and the most primitive, it is not used on many system today.
An enhanced version of the Bourne shell, called Bash, is used in Linux.
 The C shell, developed in Berkeley by Bill Joy, A compatible version of the C shell,
tcsh, is used in Linux.
 The Korn shell, developed by David Korn, also of the AT&T Labs, is the newest
and most powerful.

 Utilities

 A utility is a standard UNIX program that provides a support process for users.
Dept., of CS&E(AI & ML), RLJIT Page 6 Dr. Manjunatha B N
Module-1 Unix System Programming

 Three common utilities are text editors, search programs, and sort programs.

 Applications:

 Applications are programs that are not a standard part of UNIX.


 Written by systems administrators, professional programmers, or users, they provide an
extended capability to the system.

4. Posix and Single Unix specification


 Many versions of UNIX exist today and each of them provides its own set of API functions,
it is difficult for system developers to create applications that can be easily ported to
different versions of UNIX.
 To overcome this problem, the IEEE society formed a special task force called POSIX in
the 1980s to create a set of standards for operating system interfacing.
 Some of the subgroups of POSIX are POSIX.1, POSIX.1b & POSIX.1c are concerned with
the development of set of standards for system developers.
 Portable Operating System interface for Computer Environments (POSIX), were
developed at the behest of the Institute of Electrical and Electronics Engineers (IEEE).
 POSIX refers to operating systems in general, but was based on UNIX.
 Two standards in POSIX:
 POSIX.1: Specifies the C application program interface. Ex : system calls
 POSIX.2: Deals with the shell and utilities.
 In 2001, a joint initiative of X/Open and IEEE resulted in the unification of the two
standards. This is the Single UNIX Specification, Version 3(SUSV3)
 The “Write once, adopt everywhere”
 Means: once software has been developed on any POSIX-compliant UNIX system, it can
be easily ported to another POSIX-compliant UNIX machine with minimum
modifications.

5. General features of Unix commands/ command structure


 UNIX commands take the following general form:
$ verb [options] [arguments]
 where verb is the command name that can take a set of optional options and one or more
optional arguments.
 Commands, options and arguments have to be separated by spaces or tabs to enable the
shell to interpret them as words.
 A contiguous string of spaces and tabs together is called a whitespace. The shell
compresses multiple occurrences of whitespace into a single whitespace.
Options:

Dept., of CS&E(AI & ML), RLJIT Page 7 Dr. Manjunatha B N


Module-1 Unix System Programming

 Every command has a fixed set of options.


 The command with its arguments and options is entered in one line that is referred to as
the command line.
 Options are special type of argument that's mostly used with “-” sign.
Example:
[root@localhost ~]$ ls -l list
-rw-rw-r-- 1 root root 82 2012-01-18 16:19 list
 There must not be any whitespaces between – and l. Options are also arguments, but given
a special name because they are predetermined. Options can be normally combined with
only one – sign. i.e., instead of using
$ ls –l –a –t
-l option provides most detail of a file attributes.
-t option sorts files according to the time of modification,
-a option list the hidden file.
we can as well use,
$ ls –lat
If you use a command with a wrong option
[root@localhost ~]$ ls -z list
ls: invalid option -- 'z'
Try `ls --help' for more information.
[root@localhost ~]$ ls-l
bash: ls-l: command not found
Note: there should be space between ls and -l
Filename Arguments
 Many UNIX commands use a filename as argument so that the command can take input
from the file.
 If a command uses a filename as argument, it will usually be the last argument, after all
options.
Example:
[root@localhost ~]$ ls -lat chap01 chap02 chap03
-rw-rw-r-- 1 root root 18 2012-02-11 02:18 chap01
-rw-rw-r-- 1 root root 0 2012-02-11 02:17 chap02
-rw-rw-r-- 1 root root 15 2012-01-25 20:54 chap03
[root@localhost ~]$ cp chap01 chap02 progs / cp copies files
[root@localhost ~]$ rm chap01 chap02 / rm removes files
The command with its options and arguments is known as the command line, which is
considered as complete after [Enter] key is pressed, so that the entire line is fed to the shell
as its input for interpretation and execution.

Exceptions

Dept., of CS&E(AI & ML), RLJIT Page 8 Dr. Manjunatha B N


Module-1 Unix System Programming

 Some commands in UNIX like pwd do not take any options and arguments.
 Some commands like who may or may not be specified with arguments.
 The ls command can run without arguments (ls), with only options (ls –l), with only
filenames (ls f1 f2), or using a combination of both (ls –l f1 f2).
 Some commands compulsorily take options (cut).
 Some commands like grep, sed can take an expression as an argument, or a set of
instructions as argument.

Flexibility of Command Usage

1. Combining commands
Unix system allows you to specify more than one command in the command line. Each
command has to be separated from the other by a ; (semicolon)
Example:
wc - print newline, word, and byte counts for each file

wc note ; ls –l note / (note is a file)

2. A Command Line Can Overflow or Be split into Multiple Lines


A command is often keyed in. though the terminal width is restricted to 80 characters,
Sometimes, you will find it necessary or desirable to split a long command line into
multiple lines.
In this case, the shell issues a secondary prompt, usually >, to indicate to you that the
command line is not complete.

This can show easily with the help of echo command

[root@localhost ~]$ echo "R L jalappa institute


> of
> technology"
Out Put:
R L jalappa institute
of
technology
[root@localhost ~]$

3. Entering a Command before previous command has finished

Dept., of CS&E(AI & ML), RLJIT Page 9 Dr. Manjunatha B N


Module-1 Unix System Programming

You need not have to wait for the previous command to finish before you can enter the
next command.
Subsequent commands entered at the keyboard are stored in a buffer (a temporary storage
in memory) that is maintained by the kernel for all keyboard input.
The next command will be passed on to the shell for interpretation after the previous
command has completed its execution.

6. Understanding of some basic commands such as echo, printf, ls,


who, date, passwd, cal, Combining commands

echo: DISPLAYING A MESSAGE


we have used it in two ways:
 To display a message(like echo “Hello”)
 To evaluate shell variables(like echo $SHELL)
 echo interprets certain string known as escape sequence. An escape sequence is generally
a two character-string beginning with a \ ( backslash).
 For instance, \c is an escape sequence. When escape sequence is placed at the end of a
string used as an argument to echo, the command interprets the sequence as a directive to
place the cursor and prompt in the same line that displays the output:

$ echo “Enter filename: \c”

Enter filename: $ _ / prompt and cursor in same line

Escape sequence used by echo and printf


Escape Significance
Sequence

\a Bell

\b Backspace

\c No newline(cursor in same line)

\f Formfeed

\n Newline

\r Carriage return

Dept., of CS&E(AI & ML), RLJIT Page 10 Dr. Manjunatha B N


Module-1 Unix System Programming

\t Tab

\v Vertical tab

\\ Backslash

\ on ASCII character represented by the octal value


n,where n can’t exceed 0377(decimal value 255)

printf: AN ALTERNATIVE TO echo

The command in its simplest form can be used in the same way as echo:

$ printf “ No filename entered\n ” \n is explicitly specified

No filename entered
$ __

 printf also accepts all escape sequences used by echo.


It does not automatically insert a newline unless the \n is used explicitly.
 printf also uses formatted strings in the same way the C language function of the same
name uses them:
$ printf “ My current shell is %s\n” $SHELL // no comma before $
My current shell is /usr/bin/bash
The %s format string acts as a placeholder for the value of $SHELL(the argument), and
printf replaces %s with the value of $SHELL.
printf uses many of the formats used by C’s printf function.
Example:
%s --- String
%30s --- As above but printed in a space 30 characters wide
%d --- Decimal integer
%6d --- As above but printed in a space 6 characters wide
%o --- Octal integer
%x --- Hexadecimal integer
%f --- Floating point number

 printf can do everything that echo does, some of its format strings can convert data from
one form to another.

Dept., of CS&E(AI & ML), RLJIT Page 11 Dr. Manjunatha B N


Module-1 Unix System Programming

 Here’s how the number 255 is interpreted in octal(base 8) and hexadecimal(base 16)

$ printf “ The value of 255 is %o in octal and %x in hexadecimal\n” 255 255


The value of 255 is 377 in octal and ff in hexadecimal

ls : Listing Files

You can list the names of the files available in the directory with the ls command.
Example:

$ ls
chap01
chap02
Chap03
progs

who : WHO ARE THE USERS?


 UNIX maintains an account of all users who are logged on the system.
 The who command displays all users currently logged into the system.
Example:
$ who
root console Aug 1 07:51 (:0)
kumar pts/10 Aug 1 07:56 (pc123.heavens.com)
sharma pts/6 Aug 1 02:10 (pc125.heavens.com)
project pts/8 Aug 1 02:16 (pc125.heavens.com)
sachin pts/10 Aug 1 08:36 (mercury.heavens.com)
 The first column shows the usernames (or user-ids) of currently working on the system.
 The second column shows the device names of their respective terminals. These are
actually the filenames associated with the terminals. kumar’s terminal has the name pts/10
( a file named 10 in the pts directory).
 The third, fourth and fifth columns shows the date and time of logging in.
 The last column shows the machine name from where the user logged in.
Note:
While you're logged in to the system, you might be willing to know : who am i?
$ who am i
kumar pts/10 Aug 1 07:56 (pc123.heavens.com)

Dept., of CS&E(AI & ML), RLJIT Page 12 Dr. Manjunatha B N


Module-1 Unix System Programming

date: DISPLAYING THE SYSTEM DATE


Unix has a date command that shows the date and time in the form used on the Internet.
$ date
Wed Aug 31 16:22:40 IST 2005 / time zone here is IST
The command can also be used with suitable format specifiers as arguments.
Each format is preceded by the + symbol, followed by the % operator.
Example:
Print only the month using the format +%m
$ date +%m
08
Or the month name
$ date +%h
Aug
Or you can combine in one command:
$ date + “%h %m”
Aug 08
There are many other format specifiers,and the useful ones are listed below:
d --- the day of the month(1 to 31)
y --- the last two digits of the year.
H,M and S --- the hour, minute and second, respectively
D --- the date in the format mm/dd/yy
T --- the time in the format hh;mm;ss
Note: when you use multiple format specifiers you must enclose them within
quotes(single or double), and use single + symbol before it.

passwd: CHANGING YOUR PASSWORD


$ passwd
passwd: Changing password for kumar
Enter login password:*******
New password:*******
Re-enter new password:*******
passwd(SYSTEM):passwd successfully changed for kumar

 When invoked by an ordinary user, passwd asks for the old password, and then it demands
the new password twice.
 If everything goes smoothly, the new password is registered by the system, and the prompt
is returned.
 Depending on the way they are configured, many systems conduct certain checks on the
string that you enter as password.

Dept., of CS&E(AI & ML), RLJIT Page 13 Dr. Manjunatha B N


Module-1 Unix System Programming

 They may either disallow you from framing easy-to-remember passwords or advise you
against choosing a bad password.
 These are good practice when handling your own password:
 Don’t choose a password similar to your old one.
 Don’t use commonly used names.
 Use a mix of alphabetic or numeric characters.
 Make sure the password is meaningful enough to prevent other from guessing it.
 Don’t write down the password in an easily accessible document.
 Change the password regularly.
 When you enter a password, the string is encrypted by the system.
 Encryption generates a string of seemingly random characters that UNIX uses subsequently
to determine the authenticity of a password.
 This encryption is stored in a file named shadow in the /etc directory.

cal: The Calender


 cal is a handy tool that you can invoke any time to see the calendar of any specific month,
or a complete year.

$ cal June 2009


Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

7. Meaning of Internal and external commands


 The commands that are built-in as part of the shell are called internal commands.
Example: echo command
 A program or file having an independent existence in the /bin directory (or /usr/bin), is
called as an external command.
Example: ls, wc, cal, bc, more …

8. The type command: knowing the type of a command and


locating it

Locating Commands
 All UNIX commands are single words like ls, cat, who, etc. these names are all in
lowercase.

Dept., of CS&E(AI & ML), RLJIT Page 14 Dr. Manjunatha B N


Module-1 Unix System Programming

 These commands are essentially files containing programs, mainly written in C.

•You can find the location of an executable program using type command:
Example:-
$ type ls
ls is /bin/ls
•ls command is a file (or program) found in the directory /bin.
This means that when you execute ls command, the shell locates this file in /bin directory
and makes arrangements to execute it.

For instance entering Capital LS instead of ls

[root@localhost ~]$ LS
bash: LS: command not found
[root@localhost ~]$

9. The root login


root: The System Administrator login.
 The UNIX system provides a special login name for the exclusive use of the administrator
it is called root.
 This account doesn’t need to be separately created but comes with every system.
 Its password is generally set at the time of installation of the system and has to be used on
logging in.
login: root
Password:*******[Enter]
#_
 The prompt of root is #
 Once you login as root, you are placed in roots home directory. This directory could be /
or /root.
 On modern system, most administrative commands are resident in /sbin and /user/bin and
in older system you could find them in /etc.

10. Becoming the super user: su command


Any user can acquire superuser status with the su command if user knows the root
password.
For example, the user ravi (with the home directory /home/ravi) becomes a superuser in
this way:

Dept., of CS&E(AI & ML), RLJIT Page 15 Dr. Manjunatha B N


Module-1 Unix System Programming

$ su
Password:******** root’s password
# pwd
/home/ravi Prompt changes, but directory
doesn’t

Though the current directory doesn’t change, the # prompt indicates that ravi now
has powers of a super user.

11. The File


 The file is a container for storing information.
 Files are divided into three categories:
 Ordinary file- Also known as regular file. It contains only data as a stream of characters.
 Directory file- It’s commonly said that a directory contains files and other directories.
 Device file-All devices and peripherals are represented by files. To read or write a device,
you have to perform these operations on its associated file. Most special files are in /dev.

 Ordinary (Regular) File:


 An ordinary file or regular file is the most common file type.
 All programs you write belongs to this type.
 An ordinary file itself can be divided into two types:
1. Text file
2. Binary file

 A text file contains only printable characters, and you can view and edit them.
 All C and Java program sources, shell and perl scripts are text files.
 Every line of a text file is terminated with the newline character, also known as
linefeed(LF).

 A binary file contains both printable and unprintable characters that cover the entire
ASCII range ( 0 to 255 ).
 The object code and executables that you produce by compiling C programs are binary
files. Sound and video files are also binary files.

 Directory File:
 A directory contains no data, but keeps details of the files and subdirectories that it contains.
 A directory file contains one entry for every file and subdirectory that it houses. If you have
20 files in a directory, three will be 20 entries in the directory.
 Each entry has two components:
 the filename
 a unique identification number of the file or directory(called the inode number).
 When you create or remove a file, the kernel automatically updates its corresponding
directory by adding or removing the entry (filename and inode number) associated with the
file.

Dept., of CS&E(AI & ML), RLJIT Page 16 Dr. Manjunatha B N


Module-1 Unix System Programming

 Device File:
 You’ll also be printing files, installing software from CD-ROMs or backing up files to tape.
All of these activities are performed by reading or writing the file representing the device.
 Device filenames are found in a single directory structure, /dev.
 The kernel identifies a device from its attributes and uses them to operate the device.

12. File Name

 On most UNIX system today, a filename can consist of up to 255 characters.


 Files may or may not have extensions and can consist of practically any ASCII character
except the / and the Null character.
 You are permitted to use control characters or other unprintable characters in a filename.
 The following are valid filenames in UNIX:
.last_time list. ^V^B^D-++bcd -{}[] @#$%*abcd a..b.c.d.e
 The third filename contains 3 control characters. However, you should avoid using these
characters while naming a file.
 It is recommended that only the following characters be used in filenames:
 Alphabets and numerals.
 The period (.), hyphen (-) and underscore ( _ ).
 UNIX imposes no restrictions on the extension. In all cases, it is the application that
imposes that restriction.
Example: A C Compiler expects C program filenames to end with .c, Oracle requires
SQL scripts to have .sql extension.
 A file can have as many dots embedded in its name.Example:a.b.c.d.e is a perfectly valid
filename. A filename can also begin with or end with a dot.
 UNIX is case sensitive; cap01, Chap01 and CHAP01 are three different filenames that
can coexist in the same directory.

13. The Parent-child Relationship

 The file system in unix is a collection of all these related files (ordinary, directory
and device files) organized in a hierarchical (an inverted tree) structure.

Dept., of CS&E(AI & ML), RLJIT Page 17 Dr. Manjunatha B N


Module-1 Unix System Programming

Figure: The UNIX File System Tree


 The unix file system is that there is a top, which serves as the refrence point for all
files.
 This top is called root and is represented by a / (front slash). In this unix file system
both the name root and the symbol / to represent the root directory.
 The root directory (/) has a number of subdirectories under it. These subdirectories
have more subdirectories and other files.
 For instance, bin and usr are 2 directories under /, while a second bin & sbin are
subdirectories under usr.
 Every file, apart from root, must have a parent, and it should be easy for you to
understand as we all have our own families with similar grandparent-parent-child
relationships.
Here the home directory is the parent of kumar, while / is the parent of home, and grandparent of
kumar. If you create a file login.sql under the kumar directory, then kumar will be the parent of
this file.

14. The HOME variable: The HOME directory


 When you log onto the system, UNIX automatically places you in a directory called the
home directory.
 It is created by the system when a user account is opened. If you log in using the login
name kumar, you’ll land up in a directory that could have the pathname /home/kumar
 The shell variable HOME knows your home directory.
$ echo $HOME
/home/kumar
 What you see above is an absolute pathname, which is a sequence of directory names
starting from root (/). The subsequent slashes are used to separate the directories.

15. Relative and Absolute Pathnames


The PATH
The sequence of directories that the shell searches to look for a command is specified in
its own PATH variable.
Example:-

Dept., of CS&E(AI & ML), RLJIT Page 18 Dr. Manjunatha B N


Module-1 Unix System Programming

$ echo $PATH
/bin:/usr/bin:/usr/local/bin:/usr/ccs/bin:/usr/local/java/bin: .
There are six directories in this colon-separated list. Consider the second on /usr/bin it’s a
hierarchy of three directory name . The first is ‘/’ is the top most directory it is also called
as root, second is ‘usr’ is below the root directory and third is ‘bin’ is below the usr.
When you issue a command, the shell searches this list in the sequence specified to locate
and execute it.

1. Absolute Pathnames
 An absolute pathname specifies the full path from the root to the desired directory or file.
 A pathname that begins from root.
 The pathname usually begins with a slash / or ~
Example:
cat /home/kumar/login.sql

Note:
If the first character of a pathname is /,the file’s location must be determined with respect
to root(the first /).

When you have more than one / in a pathname, for each such /,you have to descend one
level in the file system. thus in the above example kumar is one level below home and
two levels below root

No two files in a UNIX system can have identical absolute pathnames.

You can have two files with the same name,but in different directories;their pathnames
will also be different.thus, the file /home/kumar/progs/c2f.pl can coexist with the file
/home/kumar/safe/c2f.pl.

Using the Absolute Pathname for a command


If date command resides in /bin (or usr/bin),you can use the absolute pathname:
Example
$ /bin/date

2. Relative Pathnames
A pathname that is “relative” to the location of current working directory.
 Paths that don't start with a slash(/) are always relative to the current directory.
Note : Relative pathname does NOT begin with a slash.

Example
$ cd progs
$ cat login.sql

Dept., of CS&E(AI & ML), RLJIT Page 19 Dr. Manjunatha B N


Module-1 Unix System Programming

Here, both progs and login.sql are presumed to exist in the current directory

If progs also contains a directory scripts under it, you still won’t need an absolute
pathname to change to that directory:
Example
$ cd progs/scripts //progs is in current directory

16. Directory commands – pwd, cd, mkdir, rmdir commands.

pwd : Checking your Current directory


 A user is placed in a specific directory of the file system on logging in.
 You can move around from one directory to another, but at any point of time, you are
located in only one directory. This directory is known as your current directory.
 At any time, you should be able to know what your current directory is, the pwd (print
working directory) command tells you that,
$ pwd
/home/kumar

cd: changing the current directory


 You can move around in the file system by using cd ( change directory) command.
 When used with an argument, it changes the current directory specified as argument,
$ pwd
/home/kumar
$ cd progs
$ pwd
/home/kumar/progs
Though pwd display the absolute pathname, cd doesn’t need to use one. ( the command
cd progs here means this: “change your subdirectory to pogs under current directory.” )
 When you need to switch to /bin directory where most of the commonly used UNIX
commands are kept, you should use the absolute pathname.
$ pwd
/home/kumar/pogs
$ cd /bin // absolute pathname is required here
because bin isn’t in current directory
$ pwd
/bin
 cd can also be used without any arguments:
$ pwd
/home/kumar/pogs
$ cd // cd used without arguments reverts to the home directory
$ pwd
/home/kumar

mkdir:Making Directories

Dept., of CS&E(AI & ML), RLJIT Page 20 Dr. Manjunatha B N


Module-1 Unix System Programming

 Directories are created with the mkdir command.


 A directory patch is created under the current directory like this.
$ mkdir patch
 You can create number of directories with one mkdir command.
$ mkdir patch dbs doc
Creates three directories under current directory
 You can also create directory trees with one mkdir command
$ mkdir pis pis/progs pis/data
 In the above example Creates a directory tree with pis as a directory under the current
directory and progs and data as subdirectories under pis
Note: the order of specifying the arguments is important, you obviously can’t create a subdirectory
before creation of its parent directory.
The system may refuse to create a directory due to the following reasons:
1. The directory already exists.
2. There may be an ordinary file by the same name in the current directory.
3. The permissions set for the current directory don’t permit the creation of files and directories by
the user.

rmdir:Removing Directories
 The rmdir (remove directory) command removes directories. A directory needs to be
empty before you can remove it. If it’s not, you need to remove the files first.
 Also, you can’t remove a directory if it is your present working directory; you must first
change out of that directory.
 You cannot remove a subdirectory unless you are placed in a directory which is
hierarchically above the one you have chosen to remove.
$ rmdir pis ---directory must be empty---
 Like mkdir, rmdir can also delete more than one directory in one shot.
$ rmdir patch dbs doc --removes three directories --
 You can also delete directory trees with one mkdir command
$ rmdir pis pis/progs pis/data -Shows error as pis directory is not empty-
 Note that when you delete a directory and its subdirectories, a reverse logic has to be
applied.
Eg : $ rmdir pis/data pis/progs pis --- directory tree deleted----

17. The dot (.) and double dots (..) notations to represent
present and parent directories and their usage in relative path
names.
. . -> Represents parent directory
. -> Represents current directory
Example 1
$ pwd

Dept., of CS&E(AI & ML), RLJIT Page 21 Dr. Manjunatha B N


Module-1 Unix System Programming

/home/kumar/progs/data/text
$ cd . . // moves one level up
$ pwd
/home/kumar/progs/data

Example 2
$ pwd
/home/kumar/progs/data/text
$ cd . . / . . // moves two levels up
$ pwd
/home/kumar/progs

18. File related commands – cat, mv, rm, cp, wc and od


commands

cat: Displaying and creating files


 cat is one of the most well-known commands of the UNIX system.
 It is mainly used to display the contents of a small file on the terminal.
$ cat a1
cat, like several other UNIX commands, also accepts more than one filename as arguments:
$ cat chap01 chap02
The contents of the second file are shown immediately after the first file without any header
information.
cat options( -v and –n )
There are two cat options that you may find useful.
Displaying Nonprinting Characters ( -v )
 cat is normally used for displaying text files only. Executables, when seen with cat,
simply display junk. If we have nonprinting characters in your input, we can use with –v
option to display these characters.
Numbering Lines( -n )
 The –n option numbers lines. C compilers indicate the line number where errors are
detected, and this numbering facility often helps a programmer in debugging programs.
 vi editor can show line numbers too, we can number the line in cat command using
(-n)optons.
Using cat to Create a File
 To create a small files
 Enter the command cat followed by the > character and the filename (for example, foo).
$ cat > foo

[Ctrl-d]
$_

Dept., of CS&E(AI & ML), RLJIT Page 22 Dr. Manjunatha B N


Module-1 Unix System Programming

 When the command line is terminated with [Enter] , the prompt vanishes. cat now waits
to take input from the user. Finally press [ Ctrl-d ] to signify the end of input to the
system.

cp: Copying a File


 The cp ( copy ) command copies a file or a group of files. It creates an exact image of the
file on disk with a different name.
 The syntax requires at least two filenames to be specified in the command line. When
both are ordinary files, the first is copied to the second.
$ cp chap01 unit1
 If the destination file (unit1) doesn’t exist, it will first be created before copying takes
place.
 If not, it will simply be overwritten without any warning from the system. So be careful
when you choose your destination filename.
 If there is only one file to be copied, the destination can be either an ordinary or directory.
You then have the option of choosing your destination filename.
 The following example shows two ways of copying a file to the progs directory.
cp chap01 progs/unit1 chap01 copied to unit1 under progs
cp chap01 progs chap01 retains its name under progs
 cp is often used with the shorthand notation, . (dot) to signify the current directory as the
destination. To copy the file profile from /home/sharma to your current directory we can
use either of the two commands.
cp /home/sharma/profile . Destination is the current directory
cp /home/sharma/profile profile Destination is a file
 cp can also be used to copy more than one file with a single invocation of the
command. In that case, the last filename must be a directory.
 For instance, to copy the files chap01, chap02 and chap03 to the progs directory, you
have to use cp like this:
$ cp chap01 chap02 chap03 progs
Note: the directory should be present, cp cannot create a new directory and it overwritten the
previous content.
cp Options
Interactive Copying(-i)
 The –i option warns the user before overwriting the destination file. If unit1 exists,
cp prompts for a response:
$ cp –i chap01 unit1
cp: overwrite unit1 (yes/no) ? y
A y at this prompt overwrites the file, any other response leaves it uncopied.

rm: Deleting Files


 Files can be deleted with rm (remove).
 It can be delete more than one file with a single invocation.
 The following command deletes the three files
$ rm chap01 chap02 chap03
Note: a file once deleted can’t recovered. rm won’t remove a directory, but can remove a file
from one.

Dept., of CS&E(AI & ML), RLJIT Page 23 Dr. Manjunatha B N


Module-1 Unix System Programming

$ rm progs/chap01 progs/chap02
rm Options
Interactive Deletion (-i)
 Like in cp, the –i option makes the command ask the user for confirmation before
removing each file:
$ rm -i chap01 chap02 chap03
rm: remove chap01 (yes/no) ? y
rm: remove chap02 (yes/no) ? n
rm: remove chap03 (yes/no) ? [Enter] //No reponse--- file not deleted
 A y removes the file, any other response leaves the file undeleted.
mv: Renaming Files
 The mv command renames (moves) files. It has two distinct functions:
1. It renames a file (or directory).
2. It moves a group of files to a different directory.
 mv doesn’t create a copy of the file, it merely renames it. No addition space is consumed
on disk during renaming.
 To rename the file chap01 to man01, you should use
$ mv chap01 man01
 It can move group of files can be moved to a directory. The following command moves
three files to the progs directory.
$ mv chap01 chap02 chap03 progs
 mv can also be used to rename a directory, for instance, pis to perdir:
$ mv pis perdir

wc: Counting Lines, Words and Characters


 UNIX features a universal word counting program. It counts line, words and characters,
depending on the options used.
 It takes one or more file name as argument, displays a four-columnar output.
$ cat infile
I am the wc command
 You can now use wc without options to make a word count of the data in the file:
$ wc infile
1 5 19 infile
 wc offers three options to make a specific count. The –l option counts only the number of
lines, -w and –c counts the words and characters.
$ wc –l infile
1 infile
$ wc –w infile
5 infile
$ wc –c infile
19 infile
 When used with multiple filename
$ wc chap01 chap02
10 50 250 chap01
50 500 2750 chap02
60 550 3000 total

Dept., of CS&E(AI & ML), RLJIT Page 24 Dr. Manjunatha B N


Module-1 Unix System Programming

od: Displaying Data in Octal


 Many files (especially executables)contain nonprinting characters, and must UNIX
command don’t display them properly.
 The file odfile contains some of these characters that don’t show up normally.
$ more odfile
white space include a
 The apparently incomplete first line actually contains a tab. The od command makes
these commands visible by displaying the ASCII octal value of its input.
 The –b option displays this value for each character separately.
$ od –b odfile
0000000 127 150 151 164 145 040 163 160 141 143 145 040 151
156 143 154 165 144 145 163 040 141 040 011 012
 When –b and –c options are combined
$ od –bc odfile
0000000 127 150 151 164 145 040 163 160 141 143 145 040 151 156 143 154
w h I t e s p a c e i n c l
165 144 145 163 040 141 040 011 012
u d e s a \t \n

Assignment Questions
1. Explain the architecture of UNIX operating system with a neat diagram.
OR
Describe the relationship between the Kernel, Shell and the User with the help of a
diagram.
2. Discuss the salient features of UNIX operating system.
OR
Describe briefly the major features of the UNIX operating system.
3. What are system calls? Give two examples of system calls in UNIX operating system.
4. Discuss the following: i) the UNIX Environment ii) UNIX Structure
5. Explain internal and external commands with example.
6. Briefly explain the general features of unix commands or command structure.
7. Explain the following command with examples:
i) echo ii) printf iii) ls iv) who v) date vi) passwd vii)
cal viii) su command
8. Briefly describe: i) type command or locating command ii) login prompt
9. Explain the different file types available in UNIX.
10. With the help of a neat diagram, explain the parent-child relationship with respect to
UNIX file system. OR Illustrate with a diagram, the typical UNIX file system and
explain different types of files supported in UNIX.
11. Explain the following commands with an example:
i) HOME ii) pwd iii) cd iv) mkdir v) rmdir

Dept., of CS&E(AI & ML), RLJIT Page 25 Dr. Manjunatha B N


Module-1 Unix System Programming

12. Explain absolute path name and relative path name with example.
13. Explain the following commands with example:
i) cat ii) mv iii) rm iv) cp v) wc vi) od

Dept., of CS&E(AI & ML), RLJIT Page 26 Dr. Manjunatha B N

You might also like