The UNIX Operating System: TCS Confidential
The UNIX Operating System: TCS Confidential
TCS Confidential
1
1
UNIX Operating System
Objectives :
Learn about the Unix Operating System and develop the skills
required to build software applications in the Unix Environment.
TCS Confidential
2
2
Contents :
TCS Confidential
3
3
Chapter 1
TCS Confidential
4
4
Introduction and History of UNIX
1. Evolution
2. Development
3. Standard release- AT&T versions
4. BSD UNIX
5. Other implementations of UNIX
6. Features of UNIX 5
7. UNIX Philosophy
8. UNIX operating system
9. UNIX Kernel
10. Programming Environment
11. Design Principles
12. Limitations
TCS Confidential
5
5
Evolution
MULTICS
- Developed for GENERAL ELECTRIC 645
mainframe computer
- Interactive operating system
6
- Batch - mode characteristics
6
6
Development
* Originally written in assembly language for
PDP-7
* Transportability facilitated by Thompson who
7
developed the B language
* B language modified by Ritchie and renamed
as C language
* Thompson (1980) and others wrote UNIX in
C which could be ported to any computer
TCS Confidential
7
7
Standard release - AT&T Versions
Version 3 Written in C
Moved to PDP - 11/45 and
PDP - 11/70
Version 6 Released in 1975
For
8 use by universities only
Version 7 Released in 1978
First commercial version but
primarly used in universities
32V - VAX version
Version 8 UNIX Support Group(USG)
takes responsibility
Research Group still busy TCS Confidential
8
8
Standard release - AT&T Versions Contd...
System III Released in 1981
Commercial orientation
Over 100 manufacturers of UNIX-based
micro , mini and mainframes
UNIX users > 100,000
System V
Release 1 Released
9 in 1983
Enhancement of System III
System V
Release 2 Released in 1984
Enhancements of System V , Release 1
System V
Release 3 Released in 1988
System V
Release 4.0
TCS Confidential
9
9
BSD UNIX
(from Berkeley Software Distributions)
* UNIX's entry into University of California, Berkeley Campus during 1976-77
* Inputs of UCB Faculty/researchers incorporated in System V of AT&T UNIX
TCS Confidential
1
10
Other Implementations of UNIX
(based on Version 7, System III, System V of AT&T UNIX or UNIX 4.2 BSD)
1
11
UNIX Features
1
12
UNIX Features
TCS Confidential
1
13
* Available on micros, minis and mainframes
* UNIX Communication and electronic mail
Communication between different terminals
hooked to same computer
Communication between computers of different
sizes and types in different
14 locations as far away
as other countries
* Incorporation of third party application programs
* Hierarchical File System
* On-Line Help facility
Example : man <Command>
* Library of application software
TCS Confidential
1
14
The UNIX Philosophy
TCS Confidential
1
15
The UNIX Operating System
1
16
The Users
Shells and Commands
Compilers and Interpreters
System Libraries
System Call Interface to Kernel
Signal File System CPU Scheduling
1
17
The UNIX Kernel
File Management
Networking And Security
Services
Input / Output
Date and Time
Services
Services
18
UNIX
SYSTEM Process
Signal
Scheduling
Handling KERNEL
System
Memory
Administration
Management
and Accounting
TCS Confidential
1
18
The Programming Environment
TCS Confidential
1
19
The Design Principles
TCS Confidential
2
20
Drawbacks of UNIX
TCS Confidential
2
21
Chapter 2
22
File System
TCS Confidential
2
22
The UNIX File System
TCS Confidential
2
23
File Systems in UNIX
Disks are partitioned into File Systems.
- Logical blocks of 512 bytes or multiples
- Arranged to form a hierarchical structure
- Convenient to manage data
2
24
Classification of files in UNIX
- Ordinary Files
- Directory Files
- Special Files25
- Standard Files
TCS Confidential
2
25
Concept of Ordinary Files
* A File in UNIX is a Stream of bytes ( 8-bits)
Kernel does not impose a structure on files
Examples
Text Files : Lines of ASCII characters
separated by a new-line
26
Commands : Sequence of commands
interpreted by UNIX text
2
26
Concept of Directory Files
* Gathering together related files in a common place
Examples
2
27
Concept of Special Files
* Used to reference Physical devices such as terminals, disks, floppy drives and
tape drives
2
28
Concept of Standard Files
TCS Confidential
2
29
File Names
3
30
Path Names
Absolute Path name
* If a "/" does not precede a file name then the name interpretation
begins with the current directory
e.g.,
If current directory is
/usr/trg
then the file could be just referenced as c/test.c
TCS Confidential
3
31
Features
* Hierarchical
* Removable
* File Independence -
3
32
Unix spell
console bin troff
lp0 ---
dev
tty0 src
man
sh uch
bin csh ---
bin
--- local
33 lib
Libc.a
lib ---
---
/ usr include *.h
spool tmac
passwd lib troff
etc group ---
init tmp
---
tmp
--- TCS Confidential
3
33
Standard File Hierarchy
/lib 34Unix
Libraries used by libc.a
3
34
/usr/games - Game Programs
TCS Confidential
3
35
Security and Access Methods
TCS Confidential
3
36
Starting and Ending a Session
login : User can type his name and password to identify himself
su setuser
37
This is used to become another user or super-user provided the
password is known.
e.g., $su
Prompt the user for the password of user trg2 $su - trg2 -c "ls -l"
3
37
Starting And Ending A Session Contd.
passwd Change the password for the user
e.g., $ passwd
38
logout This command exits or logs-out from the current user
and executes the file .logout before coming out
e.g., $ logout
or
$ exit
or
$ <ctrl-d>
3
38
File Management Utilities
cd cmp passwd
pwd comm crypt
mkdir chown
rmdir chgrp
mvdir 39 umask
chmod
3
39
mkdir creates a new directory
rm removes a file
du displays40
disk usage
4
40
Command Structure
General Structure:
Command Name [Options] [Arguments]
E.g.,
Command Name
Tells the shell what to do
(in this case list files)
Options
Control how the41command will work
(in this case ask for a long listing)
Arguments
on which the command works
(in this case the directory
usr/trg )
4
41
Directory Management
4
42
rmdir Remove a Directory
$ rmdir pathname
TCS Confidential
4
43
File Contents
TCS Confidential
4
44
$ cat f1 > f2 Takes input from file f1 & puts it
on file f2
$ cat f2 > f3 f3 contains the contents of f1
$ cat f4 >> f3 Appends
45 the contents of f4 to
file f3
$ cat try[0-3] > final The file final contains contents
of try0, try1, try2 try3
$ cat test* > report The file report contains all files
beginning with test
TCS Confidential
4
45
Is[Options] List the Directory Contents
TCS Confidential
4
46
$ Is -I List the files along with the protection bits and the user
$ Is -1 symtab.c
symtab.o
treegen
test
$ Is -a .
..
.profile
.cshrc
symtab.c
...
TCS Confidential
4
47
wc Word Count
$wc [Options] filename
nl no. of lines in the file and temply lists out the file
Similar to wc -l < filename >
TCS Confidential
4
48
file Determine file types
$file [Options] [Arguments]
Options -f filelist
Normal File Types
- C49program text
- assembler program text
- commands text
- ASCII text
- English text
TCS Confidential
4
49
cp copy a file
e.g.,
$ cp test.c test.c.bak
test.c and test.c.bak contain the same contents
Extra disk storage
50
In Create link
e.g.,
$ ln first.c second.c
The file is referenced by two different names
No Extra disk storage
TCS Confidential
5
50
mv Moves or renames files and directories
-i interactive mode
e.g.,
$ mv old.c new.c
Renames the file old.c as new.c
rm Deletes the indicated file(s) files
5
51
File Comparison
If files are same no output is sent to the terminal, or else The line
number and the byte at which the first difference occurs is reported
Return code
52
0 if files are identical
1 if files are different
2 on error
e.g.,
$ cmp test1 test2
test1 and test2 differ in char 36 line 3
$ cmp -s test1 test2
$ echo $status
5
52
diff - Reports more than one differences
e.g., 53
$ diff test1 test2
Outputs: n1 a n3,n4
n1,n2 d n3
n1,n1 c n3,n4
TCS Confidential
5
53
comm Display common lines
$comm -[123] f1 f2
Prints a three column output:
- lines that occur only in f1
- lines that occur only in f2
- lines that occur in both
comm -12 - prints
54 lines common to the two files
comm -23 - prints only lines in the first file but not in the
second
comm -123 - prints nothing
e.g.,
TCS Confidential
5
54
File Compression
$ pack <filename>
TCS Confidential
5
55
Mountable File System
TCS Confidential
5
56
File Security
chown To change
57
the ownership of the file
5
57
chmod change the permissions of the file
e.g., 58
$ chmod a=rw test.c
* users, group, others have read
and write permissions
TCS Confidential
5
58
umask Set file creation mode mask
$ umask nnn
(nnn set file creation mode)
umask can also be set as a shell variable
59
e.g.,
umask 022
- Files normally created with 777 mode is assigned
755 permission
TCS Confidential
5
59
File Operation
split Splits the file into different files as specified by the number of lines
e.g., $ split -20 test.c 60
Splits the file test.c in blocks of 20 lines and creates files xaa, xab, xac
6
60
Chapter 3
61
BASIC UTILITIES
TCS Confidential
6
61
Basic Utilities
1. Line Editor Ed
2. Visual Editor Vi
3. Debuggers
62
4. Profiling Tools
5. C-Beautification
TCS Confidential
6
62
The Line Editor - ed
Prompt :
Ed has no formal prompt
P - Prompts with a * This is a toggle function
Append:
a - Appends given text after current line
Write :
w - Writing to the file
Exiting ed :
q - Quit
63from ed
Example :
$ ed test.c
? test.c
P
*a
<>
<>
<>
*w
*q
The edit buffer can be written to some other file also as *w filename
TCS Confidential
6
63
Pattern Matching
abc abc
a*bc abc, aabc, aaa...bc
a.c abc, aac, acc, axc, a$c
a.*c abc, axyc, a$+pmc, abcdefgc
a[b2m]c abc, a2c, amc
a[0-2b-d]c a0c,
64 a1c, a2c, abc, acc,
adc
a[^0-2]c a3c, a5c, axc, ....
a[xy]*c ac, axc, axxc, ayyyc
a\{3,\} aaa, aaaa - 3 or more as
a\{3,5\} aaa, aaaa, aaaaa
between 3 & 5 as
TCS Confidential
6
64
Adding and Replacing Text..
TCS Confidential
6
65
Traversing within a file
+n Move up by n lines
-n Move down
66 by n lines
*$= Prints total
no. lines but
$ points to the last line does not
changecurrent
, short for 1,$
line
; short for .,$
TCS Confidential
6
66
Modifying Text
Note : The above commands can be easily remembered by associating them with the
first characters of their action. 67
Substitute Commands
TCS Confidential
6
67
Finding Text
// forward search
?? backward search
TCS Confidential
6
68
Command Execution
Command Explanation
TCS Confidential
6
69
Special ed Commands
Command Explanation
r read current
70 file after current line
TCS Confidential
7
70
The ex editor
* an improved version of ed
* less terse
* provides display options like numbered
71
line
* allows shorthand versions of commands
* clear response for error messages
TCS Confidential
7
71
The vi - Visual Editor
The editor
* Powerful full screen editor
* vi v/s ed, ex
* Mostly single key stroke commands
* Interface with ex
* Macro facility
* Ability to process text
72
Invoking $ vi filename
e.g., $ vi pgm.c
Modes :
* Command mode
* Insert mode
* From Insert mode Pressing
<ESC> remitts Command mode
TCS Confidential
7
72
Types of commands
* vi-commands (invisible)
Command mode
TCS Confidential
7
73
Format of commands
[count] command [operand]
Use . to repeat last command
Use u to undo last command
Cursor Movement
Line Oriented :
74
^ or (zero) beginning of line
$ end of line
Character oriented
h move left
l move right
j move down
k move up
TCS Confidential
7
74
Format of commands (contd.)
Word Oriented :
TCS Confidential
7
75
Block Oriented :
) move forward one sentence
( move backward one sentence
} move forward one para
{ move backward one para
% move to find matching parenthesis
Rightly used in C- Programming for matching ( & )
76
m mark a particular line with a label.
e.g., ma (marks the line with label a)
return cursor to position (m)
e.g., "a moves the cursor to the line
which was marked with label a
^g file information, line number
TCS Confidential
7
76
Text Manipulation
Insert mode :
a append after cursor
A at end of line
i insert at cursor
I at beginning of line
o enter in new line after current line
O 77in before current line
enter
esc to exit insert mode
Delete mode :
u undo last command
nx delete n- next character
ndw deleting n next words
ndd deleting n lines -
current line and n-1 below current
line are deleted.
D delete till end of line
TCS Confidential
7
77
Changing Text :
nr replace char
s delete current char, enter insert mode
S delete line, enter insert mode
cw change word
p print buffer
Join :
TCS Confidential
7
78
Search
tc similar to79
f, cursor placed 1 char left of c
TCS Confidential
7
79
Search
File Related :
8
80
Text Manipulation
Screen Adjustments :
^b Page backward
8
81
Text Manipulation
82
/string for searching forward
8
82
Common Set commands
TCS Confidential
8
83
Text Manipulation
:q quit normally
84
:q! quit, no write
TCS Confidential
8
84
Debuggers :
Why ?
Types
8
85
Debugger - sdb
* Invoked as
e.g., $ cc -g test.c
$ sdb a.out 86
8
86
SDB Commands
Command Explanation
8
87
sdb Commands (contd.)
Command Explanation
TCS Confidential
8
88
sdb Commands (contd.)
Command Explanation
TCS Confidential
8
89
CTRACE - Debugger
TCS Confidential
9
90
CTRACE - Debugger (Contd .)
* Invoked as
ctrace [options] < source-file > traced-file
options :
-o print the variable in octal
-x 91 in hex
print the variable
TCS Confidential
9
91
e.g.,
$ ctrace < test.c > ctest.c
test.c - source file
ctest.c - traced file
Compile the traced file as
92
$ cc ctest.c
creates in a default file a.out
Run the executable
$ a.out <arguments>
arguments are optional
Outputs the values of variables and statements as desired by the
user
TCS Confidential
9
92
PROFILING TOOLS :
9
93
Example of prof
$ cc -p test.c
$ a.out
$ prof a.out
Generates an output like....
%time cumsecs seconds #calls msec/call
name
91.2 9.34 9.34 20100 _func2
7.2 10.08 0.74 1 acnt
1.0 10.18 0.10 94 100 _func1
0.0 10.24 0.06 1 _main
TCS Confidential
9
94
CB - C Beautification
* Improves readability
* Invoked as
95
$ cb < source-file > target-file
e.g.,
9
95
Chapter 4
96
Shell Features
TCS Confidential
9
96
Shell Features
Shell Features
TCS Confidential
9
97
Various types of Shells :
1. Bourne Shell sh
2. C Shell csh
98
3. Korn Shell ksh
TCS Confidential
9
98
Shell Commands
TCS Confidential
9
99
; sequential execution
1
100
# rest of the line is a comment
... run command within backward quote
... treats ... literally
TCS Confidential
1
101
PATH
e.g.,
PATH = :.:/usr/bin:/bin:
TCS Confidential
1
102
Shell Startup Dot files
* Executes .logout for C Shell when user logs out from C-Shell
103
* Keeps track of the history mechanism In C Shell through the .history
TCS Confidential
1
103
Shell Variables
User defined
assignment : name = value
$ PATH=$PATH:/usr/games
$ export PATH
$ echo $PATH
:.:/usr/bin:/bin:/usr/games:
TCS Confidential
1
104
Positional Parameters
e.g.,
105
shellscript arg1 arg2
$0 $1 $2
TCS Confidential
1
105
Evaluation of Shell Variables
* $var value of var ; nothing if undefined
$ var=hello
$ 106
varx=goodbye
$ echo $var
hello
$ echo $varx
goodbye
$ echo ${var}x
hellox
TCS Confidential
1
106
* $ {var?message} If defined , $var
Otherwise print message
if message not defined print
default message
e.g.,
$ echo ${var?}
hello
$ 107
echo ${junk?}
junk : parameter not set
TCS Confidential
1
107
* ${var=thing} Value of var if defined ; otherwise thing
$var is set to thing
e.g.,
$ echo $ {junk-Hi there}
Hi there
$ echo ${junk?}
108
junk : parameter not set
$ echo ${junk?}
Hi there
1
108
Command Environment
Shell 1
109
Shell 2
Export A
e.g.,
export A
1
109
Predefined Special Parameters
$? exit value110
of last command
TCS Confidential
1
110
Variables Used by Bourne Shell in .profile
PS2 111
secondary system prompt
TCS Confidential
1
111
The C Shell
* Permits aliasing
TCS Confidential
1
112
The variables can be defined using a set for C-
Shell variables
TCS Confidential
1
113
History - Records previous commands ! is used to execute
previous command
Command Format :
! <event> [ <word> <modifier> ]
<event> - absolute !1
- relative !-3
- name !c
expr 114
!?su?
<modifier> - Substitute
:s/trg1/trg
- Print only
:s/trg1/trg/p
TCS Confidential
1
114
History Mechanism
Keeps track of commands
1
115
Changing Commands
:S/pattern/replacement
e.g.,
116
% !cd:s/trg/trg1
cd /usr/trg1/src
TCS Confidential
1
116
Using Arguments
!$ last argument
!^ Begin argument
!* All117
arguments
e.g.,
%ls !15:2-4
TCS Confidential
1
117
Alias mechanism
Short names for frequently-used long commands
e.g.,
TCS Confidential
1
118
Filename Grouping
%ls {/usr/bin,/bin}/{ls,more}
/usr/bin/ls : not found
/bin/ls
/usr/bin/more
/bin/more : not found
TCS Confidential
1
119
Using C - Shell
e.g.,
% cc test.c
% vi test.c
% !c
% a.out
% !v 120
% !c - o test
% test
% car /usr/trg2/document/report
% !! : s/car/cat
or
% ^car ^cat
TCS Confidential
1
120
Variables in .cshrc of C SHELL
% set variable=value
histchars :
% set histchars=";,"
will thereafter use
; as execution character
121 character
, as substitution
history :
% set history=40
path:
% set path=:.:/bin:/usr/bin:
prompt :
% set prompt=\!>
TCS Confidential
1
121
Variables in .cshrc of C SHELL
TCS Confidential
1
122
Test Conditions
TESTing Strings
TCS Confidential
1
123
To algebraically compare variable values
File related
124
$ test -f file True if file exists and is an ordinary file
$ test -s file True if file exists and has size greater than zero
TCS Confidential
1
124
Shell Programming
- The Bourne Shell
Control flows
if command
then
commands
[ elif commands ] ...
[ else commands ]
125
fi
TCS Confidential
1
125
for name [ in word ...]
do
commands
done
while command
do
126
commands
done
until command
do
commands
done
TCS Confidential
1
126
break n exit from for / while / until from level n
TCS Confidential
1
127
Examples
$ for i in *.dat
> do
> size=wc -c $i
> if test $size -eq 0
> then
> rm $i
> fi
> done 128
- The complete for loop can also be edited in a file and, by granting the
execute permission on the file , the Shell program can be invoked
- By default any shell program is parsed to Bourne shell
TCS Confidential
1
128
Example
echo If you have a TTY vt100 enter vt100
echo If you have a TTY AT386-M enter AT386-M
echo If you have a TTY sma84 enter sma84
read term
case $term in
vt1001) TERM=vt100
;;
AT386-M) TERM=AT386-M
;;
129
sma84) TERM=sma84
;;
*) echo Invalid TERM
;;
esac
# Making it is an environment variable
export TERM
echo end of program
This can be a part of your .profile
TCS Confidential
1
129
Control Flows
IF if (expr) then
command;
[ else if ]
command;
[ else ]
command;
endif
SWITCHswitch (string) 130
case string1:
command;
breaksw
case string2:
command;
breaksw
default :
command;
breaksw
TCS Confidential
1
130
FOREACH foreach name (word)
commands
end
1
131
Chapter 5
132
Advanced Utilities
TCS Confidential
1
132
Advanced Utilities
1. Redirection
2. Pipes
3. Pipe fitting with tee utility
4. Filters
5. Find
6. Sort
7. Utilities that process tabular data- cut, join, csplit
8. Ps and Kill133
9. Timely Execution- nohup, at, time
10. User backup utilities- tar, cpio, dd , doscp
11. Output related commands- pr, lpr,lp
12. Other utilities- sleep, sync, wait, clear, tr
13. Introduction to Make
14. Lint
15. Lex
16. Yacc
TCS Confidential
1
133
Redirection
Metacharacter Performs
< input
> output write
1
134
Pipes :
Metacharacter Performs
| piping
e.g., 135
Without Pipe $ cat /etc/passwd > temp
$ sort < temp
$ rm temp
1
135
A UNIX Pipeline
Standard Input
>Prgm #5 Prgm #6
Standard Output<
TCS Confidential
1
136
The TEE Utility :
e.g.,
137
$ ls *.c | tee Cflst | sort
$ cat cflst
TCS Confidential
1
137
FILTERS :
138
fgrep fast, several simple strings at one time
TCS Confidential
1
138
$ grep pattern filenames
Options :
TCS Confidential
1
139
Searching Files with grep
e.g.,
$ grep -ni func1 *.c Prints all the lines and line
numbers in files *.c that match
140 func1 ignoring the case
pattern
TCS Confidential
1
140
e.g.,
TCS Confidential
1
141
Find
To locate one or more files
find path-list cond-list action-list
1
142
actionlist
e.g.,
find / -atime 7 -print - will print files accessed in
exactly 7 days
find / -atime +7 -print - will print files accessed
earlier than 7 days
find / -atime -7 -print - will print files accessed
within 7 days
TCS Confidential
1
143
Examples
TCS Confidential
1
144
Sort
* Sort keys can be fields or lines
* A field is a string of characters separated by a field separator or new line.
Options
b ignore leading blanks and tabs
c only145
check if input file is already sorted
d dictionary order letters, digits, blanks
f ignore case
i ignore non-printable characters
n numeric sorting
r reverse order
tp use p as separator
u output only lines with unique keys
o filenameout save output in filenameout
TCS Confidential
1
145
e.g.,
TCS Confidential
1
146
uniq Finds and eliminates duplicate lines in
a file and is often used with sort
$ tsort psortfile
TCS Confidential
1
147
Processing Tabular Data
Cut
TCS Confidential
1
148
Cut (contd.)
cut -c list { file1 file2 ...}
e.g.,
cut -c 5-70 file1
cut would pass 5-70 characters from file1
TCS Confidential
1
149
JOIN
TCS Confidential
1
150
e.g.,
- 151 parameters
outputs the following
TCS Confidential
1
151
csplit context split
$ csplit [-k] [-f prefix] [-s] file name arg1 [..argn]
Options :
TCS Confidential
1
152
csplit(contd.)
e.g.,
TCS Confidential
1
153
PS, kill
$ somecommand &
5511 - pid
$ps
3432 2 0 : 24 -sh
5765 2 154 0 : 03 ps
5511 2 0 : 51 somecommand
$ kill 5511
$ ps
pid tty time command
3432 2 0 : 24 -sh
5985 2 0 : 03 ps
TCS Confidential
1
154
$ stubborn-cmd &
$ ps
pid tty time
155 command
3432 2 0 : 24 -sh
6004 2 0 : 03 ps
5995 2 0 : 44 stubborn-cmd
$ kill -9 5995
$ ps
pid tty time command
3432 2 0 : 24 -sh
6103 2 0 : 03 ps
TCS Confidential
1
155
Timely Execution :
1
156
nice * Executes at specified priority
* Default priority is 24
$ nice n set157
priority
$ at 5 pm
echo ^G ^G Time to logoff >/dev/tty04
^D
$
TCS Confidential
1
157
User Backup Utilities :
Options : 158
1
158
tar (example)
$ tar cvf /dev/fd096 * copies all files from the current directory
onto the backup medium /dev/fd096
$ tar xvf /dev/fd096 Extracts all the files from the backup medium
/dev/fd096 onto the current directory
159
Creates necessary directories
tar xvf /dev/fd096 try.c Extracts the file try.c from /dev/fd096
1
159
cpio * Copy files archives in and out
* Bundles all the files into one package
cpio [options] file list devicename
Options
1
160
cpio (Examples)
Lists the files *.c and copy onto the device /dev/rmt/0n
161
$ cpio -ocBv < filelst > /dev/rct/c0s0
Copies all the files mentioned in filelst onto the catridge tape
Extracts all the files from device c0s0 and creates necessary required directories
1
161
dd convert, reblock, translate, copy a tape file.
dd {option = value }
Options Values
1
162
doscp Copy a UNIX file in DOS format
or
Copy a DOS file in UNIX format
163
e.g.,
$ doscp a:try.c . copies the file try.c from the floppy onto
the current working directory
TCS Confidential
1
163
Output Related Commands :
1
164
pr (contd.)
$ pr myfile
prepare myfile
nov 24 : 11 : 31165
1987 myfile page 1
$ pr -t myfile
suppresses the header
1
165
lpr Print a file on the line printer
TCS Confidential
1
166
Other Utilities
1
167
df displays no. of free blocks
df [option] file system
1
168
make - An Introduction
* Simple mechanism
169 for maintaining an up-to-date
version of Programs
1
169
make : AN INTRODUCTION Contd...
make program takes the file named makefile or Makefile as its input.
makefile details:
- the names of the files that make up the program system
- their interdependencies
- 170
how to regenerate the program system
Example :
final
1
170
make : AN INTRODUCTION Contd...
Example (contd):
Makefile or makefile
1
171
Using the Macro facility and Inference rules
QSRC = qp1.c qp2.c qp3.c
INCLUDES = lim.h com.h
OBJECTIF = qp.o qex.o libs.a
query : $(OBJECTIF)
172
cc -o query $ (OBJECTIF)
qp.o : $ (QSRC)
cc -o qp.o $ (QSRC)
1
172
Lint - C Program Checker
1
173
Lint - C Program Checker Contd...
Example :
test.c
#include <stdio.h>
main(argc,argv)
int argc;
char **argv;
{
int i,j,k,l,number,num2;
int int1, int2;
int arr[20]; 174
scanf( %d,num2);
printf(The square root of %d is %f \n,
number , sqrt(number) );
i=arr[j++];
add(int1,int2);
}
add (int1,int2,res)
int int1,int2, *res;
{
printf("The value %d", int 1 + int 2);
}
TCS Confidential
1
174
Lint - C Program Checker Contd...
test.c
warning : k , l unused in function main
1
175
Lex
% %
rules
% %
1
176
Lex Contd...
1
177
Lex Contd...
%%
yywrap()
{
return(1);
}
Invoked as
$ lex filename
$ lex lex.l
Generates
lex.yy.c
TCS Confidential
1
178
Yacc :
TCS Confidential
1
179
Yacc Contd...
Specifications Declarations
%%
rules
%%
Example
1
180
A Program using both lex & yacc
#include <stdio.h>
main()
{
yyparse();
} 181
#include y.tab.c
#include lex.yy.c
1
181
Chapter 6
182
Communication Features
TCS Confidential
1
182
Communication Features
TCS Confidential
1
183
User Communication Commands :
* Write
* Talk 184
* Post
* News
* Mesg
TCS Confidential
1
184
Mail Sends and receives mail messages between users
$ mail <loginnames>
185 user is trg)
Example : (Assume the current
$ mail trg1
$ mail recipient@remote_system.domain_info
TCS Confidential
1
185
Receiving mail
$ mail Shows the message received
? Prompt
q quit
s [file] save (defalut mbox)
w [file] write without header
d delete
n or + next message
- previous 186
r reply to the sender
m [user] mail to user
! cmd run the shell command
TCS Confidential
1
186
User Communication commands Contd...
$ talk <username>
TCS Confidential
1
187
Post Messages can be posted on a bulletin board for previewing by all
users.
TCS Confidential
1
188
Networking Commands
* uucp
* uuto
* telnet
* rlogin
* ftp 189
* rcp
* uux
* ct
* cu
TCS Confidential
1
189
uucp * allows copying files from one unix system to
another
* Refers file uuname and uulog
1
190
uuto * Simplified version of uucp
* Sends file to /usr/spool/uucppublic
TCS Confidential
1
191
Networking Commands Contd...
$ ftp
ftp > get filename Gets the file onto the current system
TCS Confidential
1
192
rcp Similar to ftp, but a much more flexible facility
1
193
ct * Connect terminal to remote terminal
* Connects your terminal to remote
terminal which is equipped with a modem
1
194
cu * connects local system to remote system
* allows you to be logged on to both simultaneously
Examples
cu -s2400 9=5557867 Connected
login
195:
~%take proposal Takes proposal from remote computer to local
computer
~%put minutes minutes.bak Vice versa of take and puts the file minutes on
the remote computer as minutes.bak
~%!comma run the command on local system
1
195
Chapter 7
196
System calls
TCS Confidential
1
196
System Calls :
1. Introduction
TCS Confidential
1
197
* Library functions and system calls
* Both are C - functions
* Difference lies in their incorporation in the UNIX System
* Library functions are referred to as add-ons
* System calls are part of the UNIX Kernel
198
* Library functions themselves use system calls and can be
expanded by the user
* System Calls generally common across UNIX versions
* System calls share the concept of fd -file descriptor
* File descriptor is an integer used to identify a file
TCS Confidential
1
198
Basic tasks in file operations
- opening files
- reading files
- writing in files
- creating files
199
- changing the permission of files
- changing the owner and group of files
- seeking to file-location
- closing files
TCS Confidential
1
199
open ()
* open() an existing file
Example :
Opening the file test in read mode and checking for the error condition
fd = open(/usr/trg/test,0);
if ( fd == -1 )
{
printf(error in opening file test);
exit(1);
} TCS Confidential
2
200
read ()
* File should be opened in read mode
int filedesc;
char *buffer;
int nbytes; 201
read() returns the number of characters read and 0 in case ofend of file (EOF)
and returns -1 on error
TCS Confidential
2
201
Example :
if ( n == -1 )
printf (Error in reading202
file test);
TCS Confidential
2
202
write ()
* File should be opened in write mode
buffer - The function takes from buffer and writes them to indicated
file
2
203
Example :
if ( n1 == -1 )
printf (Error in writing on stdout");
} 204
if ( n == -1 )
TCS Confidential
2
204
creat ()
* creat() creates a new file or overwrites on the existing file
TCS Confidential
2
205
creat () Contd...
Example :
umask(0000);
fd = creat(newfile,0666);
if ( fd == -1 )
{
printf(error in creating file
206 newfile );
}
Creates a file called newfile in mode 0666 i.e., read and write permissions for
owner, group, and others
Note : while creating a new file ensure umask is set to zero
Otherwise,
If umask had been 0022 in the environment variable, then the effective
permission would be
mode & ~0022 TCS Confidential
2
206
chmod ()
* chmod() set permissions for the file
TCS Confidential
2
207
Example :
ret = chmod(test.c,0600);
if ( ret == -1 )
{
} 208
Changes the permission of file test.c
i.e., read and write permissions for owner
TCS Confidential
2
208
chown ()
* System call chown()
group - group id
chown() returns 0 on success and returns -1 on error TCS Confidential
2
209
chown () Contd.
Example :
ret = chown(test.c,0,1);
if ( ret == -1 ) 210
{
}
Changes the owner and group of the file test.c as root and others respectively
TCS Confidential
2
210
lseek ()
* lseek() changes the position of read-write pointer for the file descriptor
211 on success
lseek() returns new-value of the pointer
returns -1 on error
TCS Confidential
2
211
lseek () Contd...
Example :
ret = lseek(fd,1000,0);
if ( ret == -1 )
{ 212
lseek(fd,1000,0) skips the first 1000 bytes of the file and starts
reading from the 1001th byte
TCS Confidential
2
212
fork ()
* fork() creates a new process which is a child process
TCS Confidential
2
213
getpid () getppid () getpgrp ()
TCS Confidential
2
214
EXAMPLE
fork () , getpid () , getppid (), getpgrp ()
#include <stdio.h>
main()
{
int id ;
int pid , pgrp ;
int ppid ; 215
id = fork();
printf (PPID - %d PID- %d id - %d \n, getppid() , getpid() ,id );
printf (PGRP - %d \n , getpgrp() );
}
TCS Confidential
2
215
EXAMPLE
fork () , getpid () , getppid (), getpgrp ()
Output
PGRP - Process-group-ID
If PID is equal to the process PGRP then the process is the group leader
TCS Confidential
2
216
wait () & execl ()
* wait() causes a parent to stop running and await the termination of a child process
Example on execl()
#include <stdio.h>
main() 217
{
int id;
printf ( Parent process \n);
if ( ( id = fork() ) == 0 )
{
printf(Statement from child process\n);
execl(/bin/date,date,0);
}
printf( Parent process again \n);
}
TCS Confidential
2
217
EXAMPLE ON execl()
Output
Parent Process
Statement from child process
Parent process again
Tue Sep 10 11:34:17 1991
Process forked two processes and parent process avoided execl() to print the
final statement i.e parent process did not wait for the child to finish
To make the parent wait for the child to finish - wait() can be used
218 as
The example on execl() gets modified
#include <stdio.h>
main()
{
int id;
printf ( Parent process \n);
if ( ( id = fork() ) == 0 )
{
printf(Statement from child process\n);
execl(/bin/date,date,0);
}
wait();
printf( Parent process again \n);
} TCS Confidential
2
218
OUTPUT OF THE MODIFIED EXAMPLE
Parent Process
TCS Confidential
2
219
220
TCS Confidential
2
220