The UNIX Operating System

220
1 1 1 TCS TCS Confidential Confidential The UNIX Operating System

description

The UNIX Operating System. UNIX Operating System. Objectives : Learn about the Unix Operating System and develop the skills required to build software applications in the Unix Environment. Contents :. 1.Introduction & History of UNIX 2.File System 3.Basic Utilities - PowerPoint PPT Presentation

Transcript of The UNIX Operating System

Page 1: The   UNIX   Operating   System

1

1

1

TCS ConfidentialTCS Confidential

The UNIX Operating System

Page 2: The   UNIX   Operating   System

2

2

2

TCS ConfidentialTCS Confidential

UNIX Operating System

Objectives : Learn about the Unix Operating System and develop the skills

required to build software applications in the Unix Environment.

Page 3: The   UNIX   Operating   System

3

3

3

TCS ConfidentialTCS Confidential

1. Introduction & History of UNIX

2. File System

3. Basic Utilities

4. Shell Features

5. Advanced Utilities

6. Communication Features

7. System Calls

Contents :

Page 4: The   UNIX   Operating   System

4

4

4

TCS ConfidentialTCS Confidential

Chapter 1

Introduction and History of UNIX

Page 5: The   UNIX   Operating   System

5

5

5

TCS ConfidentialTCS Confidential

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 7. UNIX Philosophy 8. UNIX operating system 9. UNIX Kernel 10. Programming Environment 11. Design Principles 12. Limitations

Page 6: The   UNIX   Operating   System

6

6

6

TCS ConfidentialTCS Confidential

Primarily influenced by MULTICS

MULTICS- Developed for GENERAL ELECTRIC 645

mainframe computer- Interactive operating system - Batch - mode characteristics

UNIX Operating System- First Version developed in 1969 by Ken Thompson on DEC PDP Series ( PDP - 7 )- Business, Scientific and Industrial Users

Evolution

Page 7: The   UNIX   Operating   System

7

7

7

TCS ConfidentialTCS Confidential

Development

* Originally written in assembly language for PDP-7

* Transportability facilitated by Thompson who 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

Page 8: The   UNIX   Operating   System

8

8

8

TCS ConfidentialTCS Confidential

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 use by

universities onlyVersion 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

Page 9: The   UNIX   Operating   System

9

9

9

TCS ConfidentialTCS Confidential

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 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 •

Page 10: The   UNIX   Operating   System

10

10

10

TCS ConfidentialTCS Confidential

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

UNIX 3BSD • Released in 1978• Developed by Bill Joy and Ozalp Baboglu• Added Virtual memory, Demand paging

to the VAX version 32V

UNIX 4BSD • DARPA - funded Development• Provided support for DARPA TCP/IP• C-Shell , ex/vi , new compilers for PASCAL

and LISP were addedUNIX 4.1 BSD • Released in 1981

UNIX 4.2 BSD • Released in 1983

UNIX 4.3 BSD • Latest Release

Page 11: The   UNIX   Operating   System

11

11

11

TCS ConfidentialTCS Confidential

Other Implementations of UNIX (based on Version 7, System III, System V of AT&T UNIX or UNIX 4.2

BSD)

Xenix Microsoft’s UNIX operating system to run on microcomputers

IBM PC/IX IBM PCZeus Zilog ComputersDEC Ultrix DECHP-UX HPUNIX SUNElxsi UNIX ELXSIPyramid UNIX PyramidData General UNIX Data GeneralPerkin Elmer UNIX Perkin ElmerMassComp UNIX Mass ComputersNBI UNIX NBIAmdahl UNIX Amdahl

Page 12: The   UNIX   Operating   System

12

12

12

TCS ConfidentialTCS Confidential

Multitasking Performing tasks simultaneously rather than sequentially

e.g., While printing a document , start editing another document

Each task is considered to be a process

Multi-user Several users can use the same

computer simultaneously i.e , more than one

keyboard and terminal can be connected to one

computerHighly cost-effective

Portability Easier to modify the UNIX system code for installation on a

new computer rather than write from scratch a new operating

system

UNIX Features

Page 13: The   UNIX   Operating   System

13

13

13

TCS ConfidentialTCS Confidential

UNIX System supplied tools

Integral utilities Basic Operation of Operating system like Command

interpreter or Shell

Tools Text print formatting like nroff and typesetting troff

UNIX Features

Page 14: The   UNIX   Operating   System

14

14

14

TCS ConfidentialTCS Confidential

* 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 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

Page 15: The   UNIX   Operating   System

15

15

15

TCS ConfidentialTCS Confidential

Make each program do one thing well Expect the output of one program to

become the input to another Suited for prototype development

i.e., design and build easily Modular approach

i.e., be prepared to throw and rebuild Usage of tools Building essential tools

The UNIX Philosophy

Page 16: The   UNIX   Operating   System

16

16

16

TCS ConfidentialTCS Confidential

Kernel Schedules tasks and manages data storage

Shell A program that • interprets the user commands/requests

• calls programs from memory and

• executes them one at a time or in a series

(called a pipe)

Tools & Specific capabilities added on to the OS

Applications

Kernel( Heart of Unix Operating System)

Shell Interpreter

Tools and Applications

The UNIX Operating System

Page 17: The   UNIX   Operating   System

17

17

17

TCS ConfidentialTCS Confidential

The UsersShells and Commands

Compilers and InterpretersSystem Libraries

System Call Interface to KernelSignal File System CPU

Scheduling

Terminal Swapping Page Handling

Replacement

Character Block Demand PagingI/O System I/O System

Terminal Disk & Tape VirtualDrivers Drivers Memory

Kernel Interface to the Hardware

Terminal Device MemoryController Controller Controller

Terminals Disks & Tapes Physical Memory

Page 18: The   UNIX   Operating   System

18

18

18

TCS ConfidentialTCS Confidential

File ManagementAnd SecurityNetworking

Services

Date and TimeServices

Input / OutputServices

SignalHandling

ProcessScheduling

SystemAdministrationand Accounting

MemoryManagement

UNIXUNIX

SYSTEMSYSTEM

KERNELKERNEL

The UNIX Kernel

Page 19: The   UNIX   Operating   System

19

19

19

TCS ConfidentialTCS Confidential

* A GOOD operating system !!

• Simple yet powerful• Allows building of tools, writing of small

programs and putting them together• A rich & productive environment

* A PORTABLE operating system !!• Written in C • Runs on a range of computers • Source code is available

The Programming Environment

Page 20: The   UNIX   Operating   System

20

20

20

TCS ConfidentialTCS Confidential

* Designed for Programmers* Interactive * Multiple Processes can be initiated

Foreground ProcessBackground Process

* Methods to Co-ordinate Process* Signal to communicate with processes* Files, Directories, Devices treated as files * Tree structured directories to hold files* Emphasis on program development facilities* Sources available on-line* Simplicity before efficiency

The Design Principles

Page 21: The   UNIX   Operating   System

21

21

21

TCS ConfidentialTCS Confidential

* Designed for computer professionals

* Not a real-time operating system

* File Security depends on owner

* Defective programs may keep running

Drawbacks of UNIX

Page 22: The   UNIX   Operating   System

22

22

22

TCS ConfidentialTCS Confidential

Chapter 2

File System

Page 23: The   UNIX   Operating   System

23

23

23

TCS ConfidentialTCS Confidential

1. File System Layout2. Concepts of file 3. Features of File system 4. Starting and Ending a session5. File Management utilities 6. Directory Management 7. File operation 8. Mountable File System9. File security

The UNIX File System

Page 24: The   UNIX   Operating   System

24

24

24

TCS ConfidentialTCS Confidential

Disks are partitioned into File Systems.- Logical blocks of 512 bytes or multiples- Arranged to form a hierarchical structure- Convenient to manage data

File System Layout

Boot Super Inode Datablock block list block

Boot block- generally occupies the first sector- may contain bootstrap code

Super block- Information about the file system

How large, where free and other detailsInode list

- Contains a list of inodes- One inode is the root inode

Data block- Contains file and administrative data- Allocated data can belong to that block

only

File Systems in UNIX

Page 25: The   UNIX   Operating   System

25

25

25

TCS ConfidentialTCS Confidential

- Ordinary Files

- Directory Files

- Special Files

- Standard Files

Classification of files in UNIX

Page 26: The   UNIX   Operating   System

26

26

26

TCS ConfidentialTCS Confidential

* A File in UNIX is a Stream of bytes ( 8-bits)Kernel does not impose a structure on files

* File may contain text, data and even machine language code

Examples Text Files : Lines of ASCII characters

separated by a new-line

Commands : Sequence of commands interpreted by UNIX text

Data : File containing data as

stream of bytes

Executable : File containing machine language instructions

* The files format remains unchanged but only the way the program interprets it is different

Concept of Ordinary Files

Page 27: The   UNIX   Operating   System

27

27

27

TCS ConfidentialTCS Confidential

* Gathering together related files in a common place

* Every file is assigned to a Directory

* Directories have names (maximum of 14 characters)

* A file within a Directory can itself be another Directory (A Sub-directory)

* Internally a Directory is just a file that contains - a list of file names

- their Inode Numbers and - a pointer to the actual file on the

disk

* An upper limit of around 35 sub -directories

Examples

/ ( Forward slash ) Prime or Root Directory Note - in DOS it is \

( Backward slash ) /usr Directory for the user

/usr/trg1 Sub-Directory for trg1 under Directory usr

Concept of Directory Files

Page 28: The   UNIX   Operating   System

28

28

28

TCS ConfidentialTCS Confidential

* Used to reference Physical devices such as terminals, disks, floppy drives and tape drives

* Read and written like ordinary files

* Requests cause activation of the associated Physical Device

* Device Drivers associated with each file

* Types :Character file Terminal (tty0, tty1 ) Transmits data Character by CharacterBlock file Disk Drives (hd0,fd0) Transmits data in 512 or 1024 byte chunks * Major and Minor numbers identify the hardware link

Major No.s : Indicates type of deviceMinor No.s : Different instances of the

device

Concept of Special Files

Page 29: The   UNIX   Operating   System

29

29

29

TCS ConfidentialTCS Confidential

* Helps display information on the screen* Special Names for Communication channels * Keyboard input channel is called Standard

input (stdin) - file id is 0

* Terminal Screen output is called Standard output (stdout) - file id is 1

• Diagnostic error messages (generated by a program) are sent to Standard error

(stderr) - file id is 2 ( shown on terminal screen )

* All three files are open by default at the time of login

Concept of Standard Files

Page 30: The   UNIX   Operating   System

30

30

30

TCS ConfidentialTCS Confidential

* A means for the system to identify a fileNote : Unix is case sensitive

* User accesses a file by a user-assigned file name * Can be a sequence of characters (a maximum of 14 )

* May be identified by two or more names (Multiple links to a file)

* Internally assigned a unique inode number (for a File System) * Different files can be grouped under a

directory

File Names

Page 31: The   UNIX   Operating   System

31

31

31

TCS ConfidentialTCS Confidential

Absolute Path name

* A file is identified by the path name from the roote.g.,

/usr/trg/c/test.cwhere

• test.c is an ordinary file• usr, trg, c are directories• trg is a sub-directory under usr

Relative path name

* UNIX keeps track of the user's current directory

* 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

Path Names

Page 32: The   UNIX   Operating   System

32

32

32

TCS ConfidentialTCS Confidential

* Hierarchical

* Security on each file - Owner

- Group - All others

* Separate security for - read

- write and - execute

* Removable

* File Independence -

* Time stamp on each file - Modification time

- Access time

Features

Page 33: The   UNIX   Operating   System

33

33

33

TCS ConfidentialTCS Confidential

dev

bin

lib

spool

etc

tmp

consolelp0tty0

shcsh---

---Libc.a

groupinit---

passwd

/

spelltroff---

man

---

local

uch

bin

src

lib

tmp

---

---

troff

tmac

---

lib

bin

*.hincludeusr

Unix

Page 34: The   UNIX   Operating   System

34

34

34

TCS ConfidentialTCS Confidential

/bin Basic Unix utilities cp, mv, ln

/dev Special I/O device files fd0, lp0

/etc Administrative Programs passwd, shutdown

/lib Libraries used by Unix libc.a

/usr/bin Unix utilities cal, bc,spell

/usr/adm Administrative commands and files

adduser

/tmp Temporary files created on error conditions

Standard File Hierarchy

Page 35: The   UNIX   Operating   System

35

35

35

TCS ConfidentialTCS Confidential

/usr/games - Game Programs

/usr/include - Include files for language procedure

Examples : C-header files

stdio.h, math.h /usr/lib - Archive libraries

Example : troff

/usr/mail - Mail filesExample : mailbox

/usr/news - News files

/usr/spool - Spool files

/usr/tmp - Temporary files

/usr/src - Program Source Files

Page 36: The   UNIX   Operating   System

36

36

36

TCS ConfidentialTCS Confidential

* Three levels of accessUser/Owner, group, others

* Three types of access on Files and DirectoriesRead, Write, Execute

Access Mode Ordinary Directory

Read Examination of Listing ofFile Contents files within

Directory

Write Allows changing Creating newof file contents files within

Directory

Execute Executing file as Searching thea command Directory allowed

allowed

Security and Access Methods

Page 37: The   UNIX   Operating   System

37

37

37

TCS ConfidentialTCS Confidential

login : User can type his name and password to identify himself

login command can be used as $ exec login

to log-on onto another user account after identifying yourself in response to prompts for user name and password

su setuser

This is used to become another user or super-user provided the password is known.

e.g., $su

Prompt the user for the superuser password $su - trg2

Prompt the user for the password of user trg2 $su - trg2 -c "ls -l"

Temporarily changes to trg2 and executes the command ls -l and comes back to the original user

Starting and Ending a Session

Page 38: The   UNIX   Operating   System

38

38

38

TCS ConfidentialTCS Confidential

Starting And Ending A Session …Contd….

passwd Change the password for the usere.g., $ passwd

Prompt you for old password and new password

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>

exits from the current login

Page 39: The   UNIX   Operating   System

39

39

39

TCS ConfidentialTCS Confidential

Directory Operation File Comp.SecurityManagement

cd cmp passwdpwd comm cryptmkdir chownrmdir chgrpmvdir umask

chmod

File File Mountable Copy, Movecontents compression file Remove & Time

cat pack mount cpls unpack umount lnwc mvfile rm

touch

File Management Utilities

Page 40: The   UNIX   Operating   System

40

40

40

TCS ConfidentialTCS Confidential

mkdir creates a new directory

rm removes a file

rmdir removes a directory

du displays disk usage

df displays number of free block

touch updates the time of last modification

find locates files that match certain area

file displays the type of file

pwd displays full pathname of current

directory

Page 41: The   UNIX   Operating   System

41

41

41

TCS ConfidentialTCS Confidential

General Structure:Command Name [Options] [Arguments]

E.g.,

Command NameTells the shell what to do(in this case list files)

OptionsControl how the command will work (in this case ask for a long listing)

Argumentson which the command works(in this case the directory usr/trg )

ls -l /usr/trg

Command Structure

Page 42: The   UNIX   Operating   System

42

42

42

TCS ConfidentialTCS Confidential

Directory Management

cd Change working Directorycd.. Parent Directorycd. Current Directory

e.g.,$ cd /usr/trg/c ( current Directory is c )$ cd .. ( current Directory is trg )$ cd ./c ( current Directory is again c ) or $ cd c$ cd ( home directory - in this case /usr/trg)

mkdir Make a Directory $ mkdir pathname

Makes Directory in 777 mode

Write permission should at least be permitted for owner in parent Directory

e.g.,$ mkdir /usr/trg2 ( makes directory trg2 )

Page 43: The   UNIX   Operating   System

43

43

43

TCS ConfidentialTCS Confidential

rmdir Remove a Directory$ rmdir pathname

* Directory should be empty, or elserm -r (recursively remove)

e.g.,$ rmdir /usr/trg2 (removes directory

trg2)

pwd Print Working

Directory

Page 44: The   UNIX   Operating   System

44

44

44

TCS ConfidentialTCS Confidential

cat Concatenate & Print on screen or printer$cat [Options] [Arguments]

Options - take input from stdin -n no. of output lines-s squeeze adj. blank lines-v enable display of non-printing

characters-b used with -n to avoid numbering

blank lines

e.g.,

$ cat try.c Display the contents of try.c on the screen

$ cat Takes input from stdin i.e. keyboard and displays on screen

File Contents

Page 45: The   UNIX   Operating   System

45

45

45

TCS ConfidentialTCS Confidential

$ 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 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

Page 46: The   UNIX   Operating   System

46

46

46

TCS ConfidentialTCS Confidential

Is[Options] List the Directory Contents

Options -1 number one single column output

-l long format (II also used)

-a all entries including dot files

-s gives no. of disk blocks

-i inode no.

-t ordered by modification time recent

first recursively display all directories,

starting specified or current directory

Page 47: The   UNIX   Operating   System

47

47

47

TCS ConfidentialTCS Confidential

$ Is -I List the files along with the protection bits and the user

$ Is -a List the files starting with .and..also

$ Is -1 symtab.csymtab.otreegentest

$ Is -I -rw-r—r— 1 smj proj1 30766 Mar 3 15:08 symtab.c-rw-r—r— 1 smj proj1 8759 Mar 3 15:12 symtab.o-rwxr-xr-x 4 smj proj1 40743 Mar 3 15:23 treegendrwxrwxr-x 1 smj proj1 53 Mar 1 09:15 test

$ Is -a ....profile.cshrcsymtab.c...

$ Is -iI 10936-rw-r—r—I smj proj1 3076 Mar 3 15:08 test.c10936 - inode number of file test.c

Page 48: The   UNIX   Operating   System

48

48

48

TCS ConfidentialTCS Confidential

wc Word Count $wc [Options] filename

Options - Display no. of lines, words, characters

-I Display no. of lines-w Display no. of words-c Display no. of characters

e.g., $ wc test.c20 200 567820 - lines200 - words5678- characters

nl no. of lines in the file and temp’ly lists out the file

Similar to wc -l < filename >

Page 49: The   UNIX   Operating   System

49

49

49

TCS ConfidentialTCS Confidential

file Determine file types$file [Options] [Arguments]

Options -f filelistNormal File Types- C program text- assembler program text- commands text- ASCII text- English text

e.g., $ file test.cC Program test

Page 50: The   UNIX   Operating   System

50

50

50

TCS ConfidentialTCS Confidential

cp copy a file

-i - user interactive mode

e.g.,$ cp test.c test.c.baktest.c and test.c.bak contain the same

contentsExtra disk storage

In Create link

e.g.,

$ ln first.c second.cThe file is referenced by two different namesNo Extra disk storage

Page 51: The   UNIX   Operating   System

51

51

51

TCS ConfidentialTCS Confidential

mv Moves or renames files and directories

-i interactive modee.g.,

$ mv old.c new.cRenames the file old.c as new.c

rm Deletes the indicated file(s) files

rm removes files and directories-i remove interactively-f forcible remove-r remove recursively

• Dangerous• used in conjunction with -i

touch Updates access, modification or change times of a file

-a update access time-m update modification time-c prevents creating the file

e.g., $ touch f1* The current system date & time stamp is put on the file f1* If f1 does not exist then it is created with 0 bytes

Page 52: The   UNIX   Operating   System

52

52

52

TCS ConfidentialTCS Confidential

cmp Compare two files

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

-s Outputs nothing Registers return code

Return code

0 if files are identical1 if files are different2 on error

e.g.,$ cmp test1 test2test1 and test2 differ in char 36 line 3$ cmp -s test1 test2$ echo $status

outputs 1 indicating that the files are different

File Comparison

Page 53: The   UNIX   Operating   System

53

53

53

TCS ConfidentialTCS Confidential

diff - Reports more than one differences

$diff [Options] file1 file2-b Ignores trailing blanks

-e Gives a list of ed commands so as to convert file1 into file2.

e.g.,$ diff test1 test2

Outputs: n1 a n3,n4n1,n2 d n3n1,n1 c n3,n4

where * n1 ,n2, n3 ,n4 are line numbers* a ,d, c means append, delete ,change

respectively

Page 54: The   UNIX   Operating   System

54

54

54

TCS ConfidentialTCS Confidential

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 lines common to the two filescomm -23 - prints only lines in the first file but

not in the secondcomm -123 - prints nothing

e.g.,

$ comm test1 test2 Reports the common lines between files test1, test2 and

reports the lines differing

$ comm -12 test1 test2 Prints line common to both

Page 55: The   UNIX   Operating   System

55

55

55

TCS ConfidentialTCS Confidential

pack Compress the file

$ pack <filename>

e.g., $ pack try- Creates a file try.z which is packed- Normally the executables are packed- The size is reduced by 25 - 40 %

unpack Uncompress packed fileor pcat

e.g., $ unpack try.zor$ pcat try.z

unpacks the file try.z

File Compression

Page 56: The   UNIX   Operating   System

56

56

56

TCS ConfidentialTCS Confidential

mount Associates a directory with a device

e.g., Mounting a floppy on the root file system

umount Dissociates directory from the device

e.g.,$ mount /dev/fd096 /mnt Mounts the floppy on

the directory /mnt$ umount /mnt Dissociates /mnt from

the floppy

Mountable File System

Page 57: The   UNIX   Operating   System

57

57

57

TCS ConfidentialTCS Confidential

passwd To change the password

chown To change the ownership of the file

$ chown owner filename

e.g., $ chown trg2 test.c* Initially the owner is trg1* Only the owner or the superuser

can change the ownership of the file

File Security

Page 58: The   UNIX   Operating   System

58

58

58

TCS ConfidentialTCS Confidential

chmod change the permissions of the file

$ chmod who op permission <filelist>

who a, u, g, o all, user, group, others op +, -, = + add, - remove, = set permission r,w,x r read, w write, x execute

e.g.,$ chmod a=rw test.c

* users, group, others have read and write permissions

$ chmod u+r, g+w, o+x test.c* read for users write for groups execute for others

$ chmod 777 test.c* Sets read, write, execute Permissions

Page 59: The   UNIX   Operating   System

59

59

59

TCS ConfidentialTCS Confidential

umask Set file creation mode mask

$ umask nnn (nnn set file creation mode)umask can also be set as a shell variable

e.g., umask 022

- Files normally created with 777 mode is assigned 755 permission

The value of each digit is subtracted from the corresponding "digit" specified by the system for the creation of a file.

Page 60: The   UNIX   Operating   System

60

60

60

TCS ConfidentialTCS Confidential

tail Displays the last lines of fileoptions : -n (n= no. of lines)e.g., $ tail -30 test.cDisplays the last 30 lines of file test. c

head Displays the top lines of filee.g., $ head -10 test.c Displays the first 10 lines of

test.c

split Splits the file into different files as specified by the number of lines

e.g., $ split -20 test.c Splits the file test.c in blocks of 20 lines and creates files

xaa, xab, xac and so on, such thatxaa has first 20 lines of test.cxab has the next 20 lines of test.c

...The file test.c is unaffected$ split-20 test.c try Generates files as tryaa , tryab ,

tryac

paste Joins the two or more files horizontallye.g., $ paste xaa xab File xaa and xab are joined horizontally and output to

the terminal

File Operation

Page 61: The   UNIX   Operating   System

61

61

61

TCS ConfidentialTCS Confidential

Chapter 3Chapter 3

BASIC BASIC UTILITIESUTILITIES

Page 62: The   UNIX   Operating   System

62

62

62

TCS ConfidentialTCS Confidential

1. Line Editor Ed

2. Visual Editor Vi

3. Debuggers

4. Profiling Tools

5. C-Beautification

Basic Utilities

Page 63: The   UNIX   Operating   System

63

63

63

TCS ConfidentialTCS Confidential

Invoking ed: $ ed filename

Prompt :Ed has no formal promptP - 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 from ed

Example :

$ ed test.c? test.cP*a

<————> <————> <————>

*w*q

The edit buffer can be written to some other file also as *w filename

The Line Editor - ed

Page 64: The   UNIX   Operating   System

64

64

64

TCS ConfidentialTCS Confidential

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, 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 a’s

a\{3,5\} aaa, aaaa, aaaaa between 3 & 5 a’s

Pattern Matching

Page 65: The   UNIX   Operating   System

65

65

65

TCS ConfidentialTCS Confidential

Command Explanation Usage

p print current line (s) 1,3p

l list current line(s) 2,4l(display invisible characters

like tabs etc.)

n print line(s) with number before it 1,5n

a append text after current line 4a

i insert text before current line 3i

Adding and Replacing Text..

Page 66: The   UNIX   Operating   System

66

66

66

TCS ConfidentialTCS Confidential

Command Explanation Examples

. Pointer to current line * - Previous line

.= Gives line number

n Current line is ‘n’ * - Current line

+n Move up by n lines

-n Move down by n lines

$ points to the last line

, short for 1,$

; short for .,$

/.../ forward search for string of characters enclosed between slashes

*$= Prints total no. lines but does not changecurrent line

Traversing within a file

Page 67: The   UNIX   Operating   System

67

67

67

TCS ConfidentialTCS Confidential

Command ExplanationUsage

d delete line(s) in text 2,5d

c change line(s) in text 2,4c

m move line(s) in text 2,3m5

t copy line(s) in text 2,3t5

j join lines in text 2,3ju undo last command

Note : The above commands can be easily remembered by associating them with the first characters of their action.

Substitute Commands

(n,n)s/oldstr/newstr - replaces oldstr with newstr (n,n) range of lines - optional s/oldstr/newstr/g - all oldstrs' on the current line are replaced with newstr

s/oldstr/newstr/p - the replacement is only effected in print but not executed

s/oldstr/newstr&/ - newstr is inserted at every matchs/oldstr/%/ - matched strings are replaced by the

replacement string in the most recent substitute command

Modifying Text

Page 68: The   UNIX   Operating   System

68

68

68

TCS ConfidentialTCS Confidential

/^ pattern/ searches for patterns at beginning of line

/pattern $/ searches for pattern at end of line

/pattern/ the pattern is searched forward

// forward search

?? backward search

Finding Text

Page 69: The   UNIX   Operating   System

69

69

69

TCS ConfidentialTCS Confidential

Command Explanation

(n,n)g/findstr/commandlist Executes given commandlist for every occurrence of findstr

(n,n)G/findstr/ Inputs one command to execute for every occurrence of findstr

(n,n)v/findstr/commandlist Executes given commandlist for every non-occurrence of findstr

(n,n)V/findstr/ Inputs one command to execute for every non-occurrence of findstr

Command Execution

Page 70: The   UNIX   Operating   System

70

70

70

TCS ConfidentialTCS Confidential

Command Explanation

f print current filename

w write contents of buffer into file

w file2 write contents of buffer to file 2

r read current file after current line

r file2 read contents of file2 after current line

e file2 edit file2 —> invoke ed on file2

!shellcmd Execute shell command by preceding with ‘!’ ! ls –l gives a listing of current directory

Special ed Commands

Page 71: The   UNIX   Operating   System

71

71

71

TCS ConfidentialTCS Confidential

* an improved version of ed* less terse* provides display options like

numbered line

* allows shorthand versions of commands

* clear response for error messages

The ex editor

Page 72: The   UNIX   Operating   System

72

72

72

TCS ConfidentialTCS Confidential

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

Invoking $ vi filenamee.g., $ vi pgm.c

Modes :* Command mode* Insert mode

* From Insert mode Pressing <ESC> remitts Command mode

The vi - Visual Editor

Page 73: The   UNIX   Operating   System

73

73

73

TCS ConfidentialTCS Confidential

Types of commands* vi-commands (invisible)

Command mode

Commands can be categorised as :* Cursor movement* Text manipulations - insert, delete, copy, change* Marking/Selecting, Positioning* Search

Objects of interest recognized by ‘vi’:* characters* words* lines* block

Page 74: The   UNIX   Operating   System

74

74

74

TCS ConfidentialTCS Confidential

Format of commands[count] command [operand] Use “.” to repeat last commandUse “u” to undo last command

Cursor MovementLine Oriented :

^ or (zero) beginning of line$ end of line

Character orientedh move left

l move rightj move downk move up

Page 75: The   UNIX   Operating   System

75

75

75

TCS ConfidentialTCS Confidential

Format of commands (contd.)

Word Oriented :

e move to end of next word

w move to beginning of word

b move to beginning of previous word

E move to end of next word ignoring punctuation

W move to beginning of word ignoring punctuation

B move to previous word ignoring punctuation

Page 76: The   UNIX   Operating   System

76

76

76

TCS ConfidentialTCS Confidential

Block Oriented :

) move forward one sentence

( move backward one sentence

} move forward one para

{ move backward one para

% move to find matching parenthesisRightly used in C- Programming for

matching ‘(‘ & ‘)’

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

Page 77: The   UNIX   Operating   System

77

77

77

TCS ConfidentialTCS Confidential

Text Manipulation

Insert mode :a append after cursorA at end of linei insert at cursorI at beginning of lineo enter in new line after current lineO enter in before current lineesc to exit insert mode

Delete mode :u undo last commandnx delete n- next characterndw deleting n next wordsndd deleting n lines -

current line and n-1 below current line are deleted.

D delete till end of line

Page 78: The   UNIX   Operating   System

78

78

78

TCS ConfidentialTCS Confidential

Changing Text :

nr replace chars delete current char, enter

insert modeS delete line, enter insert

modecw change word

Cut & Paste :

nyy yank n lineNamed Buffers : a to z ( 26

)Unnamed Buffers : 1

p print buffer

Join :

J join next line to current EOL

Page 79: The   UNIX   Operating   System

79

79

79

TCS ConfidentialTCS Confidential

Search

Searching for a character :

fc search forward for character ‘c’

tc similar to f, cursor placed 1 char left of ‘c’

Fc search backward for character ‘c’

Tc similar to F, cursor place 1 char right of ‘c’

; continue search in same direction

‘ continue search in reverse direction

Page 80: The   UNIX   Operating   System

80

80

80

TCS ConfidentialTCS Confidential

Search

File Related :

G go to the end line

nG go to the nth line

M go to the middle line

H go to the top line

L go to the last line

Page 81: The   UNIX   Operating   System

81

81

81

TCS ConfidentialTCS Confidential

Text Manipulation

Screen Adjustments :

^d Scroll down half a screen

^u Scroll up half a screen

^f Page forward

^b Page backward

^e exposes one more line at bottom of screen

^y exposes one more line at the top of screen

Page 82: The   UNIX   Operating   System

82

82

82

TCS ConfidentialTCS Confidential

Text Manipulation

Searching for a string :

/string for searching forward

?string for searching backward

Use n to continue search in the same direction

Use N to continue search in the opposite direction

s/oldstr/newstr commands can be used in vi

Page 83: The   UNIX   Operating   System

83

83

83

TCS ConfidentialTCS Confidential

Common Set commands

set ai Causes automatic indentation

set noai Nullifies the effect of auto-indent

set nu Causes line numbers to be displayed

set wrapmargin = n Sets n column right margin

set bf The beautify option Removes all unimportant control characters

set Causes a displays of current set options

Page 84: The   UNIX   Operating   System

84

84

84

TCS ConfidentialTCS Confidential

Text Manipulation

:w! file force write

:q quit normally

:q! quit, no write

:n next file, for $ vi f1 f2 f3 f4

:n! edit next file, discarding changes to current file

:n args specify new argument list

Page 85: The   UNIX   Operating   System

85

85

85

TCS ConfidentialTCS Confidential

Why ?

* for running a Program under the control of the programmer * for examining the values of various variables and stack contents

Types

fsdb File System Debugger Fixes damaged file system

kdb Kernel DebuggerResides in kernel, Allows memory examination Disassembles instructionsExecutes programs

sdb - Debugging source code written in C, Fortran 77

- Available on System V

Role The functionality of any debugger is essentially the same

Debuggers :

Page 86: The   UNIX   Operating   System

86

86

86

TCS ConfidentialTCS Confidential

Debugger - sdb

* Invoked as

sdb <executable file>

e.g., $ cc -g test.c$ sdb a.out

* sdb checks for the status of files

* sdb gives warning messages if source files are not present or source files were modified after the object files

* sdb gives a prompt * after invocation

* some commands can be used to avail the important features of sdb

Page 87: The   UNIX   Operating   System

87

87

87

TCS ConfidentialTCS Confidential

SDB Commands

Command Explanation

*r <arguments> run the program (arguments optional )

*s stepping through the instructions*20b setting a break point at line number 20

(Normally break points are set at function calls)

*/pattern searches for the pattern*<function-name> b setting the break point at the function name\*B gives a list of break points\*d <line-no> deletes the break point at the specified line no.*D deletes all the break points

Page 88: The   UNIX   Operating   System

88

88

88

TCS ConfidentialTCS Confidential

sdb Commands (contd.)

Command Explanation

*S stepping over the function call

*c continue upto the break point

*variable name prints the value of variable active at that time

*variable name/x prints the value of variable in hex

*variable name/c prints the value of variable in character

*variable name/o prints the value of variable in octal

*variable name/s prints the value of variable in null terminated string

*variable name/a character strings at the specified address*function:variable prints the value of the variable in the

specified function

Page 89: The   UNIX   Operating   System

89

89

89

TCS ConfidentialTCS Confidential

sdb Commands (contd.)

Command Explanation

*p print the current line of the source

*<line-no>p print the corresponding line-no of the source

*<ctr-d> prints next 10 lines of source or data or instructions depending on the previous command

*w prints a window of 10 lines of source or data or instructions around the current line

*<Enter-key> executes the previous command

*!<command> executes the shell command

*k kills the debugger

*q quits the debugger

Page 90: The   UNIX   Operating   System

90

90

90

TCS ConfidentialTCS Confidential

CTRACE - Debugger

Different from the conventional debuggers like sdb

Works in the absence of a debugger

Ctrace simulates the insertion of printf statements

– Programmer’s way of debugging is to insert printf statements at the required places

– Results in more printf statements than the program itself

Ctrace also traces infinite loops

Page 91: The   UNIX   Operating   System

91

91

91

TCS ConfidentialTCS Confidential

CTRACE - Debugger (Contd .)

* Invoked as ctrace [options] < source-file > traced-

file

options :

-o print the variable in octal-x print the variable in hex

-u print the variable in unsigned format

-e print the variable in floating point format

-f <function-names> trace only the selected function names

-v <function-names> complement of option -f trace all functions except those specified in the list

Page 92: The   UNIX   Operating   System

92

92

92

TCS ConfidentialTCS Confidential

e.g.,

$ ctrace < test.c > ctest.c

test.c - source filectest.c - traced file

Compile the traced file as

$ 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

Page 93: The   UNIX   Operating   System

93

93

93

TCS ConfidentialTCS Confidential

PROF and GPROF

* Improves efficiency and debugging

* gprof is available in BSD versions

* The program should have been compiled with -p option for prof and -g option for gprof

* prof - refers default input file mon.out

* gprof - refers default input file gmon.out

* Gives an idea as to which function used up the maximum time

PROFILING TOOLS :

Page 94: The   UNIX   Operating   System

94

94

94

TCS ConfidentialTCS Confidential

Example of prof

$ cc -p test.c$ a.out$ prof a.out

Generates an output like....

%time cumsecs seconds #calls msec/call name91.2 9.34 9.34 20100 _func27.2 10.08 0.74 1 acnt1.0 10.18 0.10 100 _func1 0.0 10.24 0.06 1 _main

%time Percentage of time consumed by the function

cumsecs Running sum or cumulative sum of the functions called

seconds Seconds consumed by the function

calls Number of times the function was invoked

name Function name

Page 95: The   UNIX   Operating   System

95

95

95

TCS ConfidentialTCS Confidential

* Beautifies the C-program code

* Indents all the statements

* Improves readability

* Invoked as

$ cb < source-file > target-file

e.g.,

$ cb < test.c > test1.c

test.c - source file

test1.c - Beautified version of test.c

CB - C Beautification

Page 96: The   UNIX   Operating   System

96

96

96

TCS ConfidentialTCS Confidential

Chapter 4Chapter 4

Shell Features Shell Features

Page 97: The   UNIX   Operating   System

97

97

97

TCS ConfidentialTCS Confidential

Shell Features

1. Various kind of shells 2. Shell commands3. Shell Startup Dot files4. Shell variables5. C Shell6. Test conditions7. Shell programming - Bourne Shell8. Shell programming - C Shell

Shell Features

Page 98: The   UNIX   Operating   System

98

98

98

TCS ConfidentialTCS Confidential

1. Bourne Shell sh

2. C Shell csh

3. Korn Shell ksh

4. Restricted Shell rsh

5. Visual Shell vsh

Various types of Shells :

Page 99: The   UNIX   Operating   System

99

99

99

TCS ConfidentialTCS Confidential

Simple commands using shell Metacharacters

Exit status - return value 0 - Successful - return value > 0 - Failure

Redirection Default input from KeyboardDefault output on the Screen

< - Read from a file> - Redirect it to a file>> - Append to a file

n>&m - Merge output from file descriptor n with file descriptor m

n<&m - Merge input from file descriptor n with file descriptor m

where n and m are file descriptors for thestdin, stdout and stderr files

Pipeline sequence of commands separated by |

Shell Commands

Page 100: The   UNIX   Operating   System

100

100

100

TCS ConfidentialTCS Confidential

; sequential execution

& asynchronous execution

&& following list executed if preceding pipeline returns

zero value

|| following list executed if preceding pipeline returns nonzero value

* matches 0 or more characters

? matches any single character in filenames

$var value of shell variable var

var=variable assign variable to var

Page 101: The   UNIX   Operating   System

101

101

101

TCS ConfidentialTCS Confidential

# rest of the line is a comment

‘...‘ run command within backward quote

‘...’ treats ... literally

“...” treats ... literally except for $ and ‘...‘ and \

e.g.,

$ (sleep 5 ; echo “The date is `date` “ ) & date

The Output of the above command will be

6345

Wed Sep 23 10:20:45 EDT 1991$The date is Wed Sep 23 10:20:50 EDT 1991

Page 102: The   UNIX   Operating   System

102

102

102

TCS ConfidentialTCS Confidential

PATH

* If full path is given while executing the command, the command is executed from the path specified

* Else it is searched in the Shell variable $PATH

* Search order is defined by value of Shell variable Path

e.g.,

PATH = :.:/usr/bin:/bin:

Page 103: The   UNIX   Operating   System

103

103

103

TCS ConfidentialTCS Confidential

Shell Startup Dot files

* Helps in customizing UNIX System

* Executes .profile for Bourne Shell when user logs on

* Executes .login and .cshrc for C Shell when user logs on

* Executes .logout for C Shell when user logs out from C-Shell

* Keeps track of the history mechanism In C Shell through the .history

Page 104: The   UNIX   Operating   System

104

104

104

TCS ConfidentialTCS Confidential

Shell Variables

User defined assignment : name = value

e.g., (on Bourne shell)

$ x=”Hello how are you”$ echo $x

Hello how are you

$ PATH=$PATH:/usr/games$ export PATH $ echo $PATH

:.:/usr/bin:/bin:/usr/games:

Page 105: The   UNIX   Operating   System

105

105

105

TCS ConfidentialTCS Confidential

Positional Parameters

e.g.,

shellscript arg1 arg2

$0 $1 $2

Page 106: The   UNIX   Operating   System

106

106

106

TCS ConfidentialTCS Confidential

Evaluation of Shell Variables

* $var value of var ; nothing if undefined

* ${var} same as $var ; useful if alphanumeric characters

follow variable name - derefrencing variable

e.g.,

$ var=hello

$ varx=goodbye

$ echo $var

hello

$ echo $varx

goodbye

$ echo ${var}x

hellox

Page 107: The   UNIX   Operating   System

107

107

107

TCS ConfidentialTCS Confidential

* $ {var?message} If defined , $varOtherwise print messageif message not defined printdefault message

e.g.,$ echo ${var?}

hello

$ echo ${junk?}junk : parameter not set

$ echo ${junk?my message error}junk : my message error

* ${var-thing} Value of var if defined , else use thing$var unaffected

Page 108: The   UNIX   Operating   System

108

108

108

TCS ConfidentialTCS Confidential

* ${var=thing} Value of var if defined ; otherwise thing $var is set to thing

e.g., $ echo $ {junk-’Hi there’}

Hi there

$ echo ${junk?}junk : parameter not set

$ echo $ {junk=’Hi there’}Hi there

$ echo ${junk?}Hi there

* $ {var+thing} If var defined then thing Otherwise nothing

Page 109: The   UNIX   Operating   System

109

109

109

TCS ConfidentialTCS Confidential

Command Environment

* Variables & associated values

e.g., export A

* Export from parent to child shell

* Vice-versa not true

Shell 1

Shell 2

Export A

Page 110: The   UNIX   Operating   System

110

110

110

TCS ConfidentialTCS Confidential

Predefined Special Parameters

$# number of positional parameters

$? exit value of last command

$$ process number of a process

$* all the parameters

$! process id of last command started with asynchronous execution i.e., &

Page 111: The   UNIX   Operating   System

111

111

111

TCS ConfidentialTCS Confidential

Variables Used by Bourne Shell in .profile

CDPATH search path for cd

HOME login dir

PATH search path for commands

PS1 primary system prompt

PS2 secondary system prompt

IFS internal field separator

MAIL files containing mail messages

TERM terminal type

EXINIT list of set commands for vi

Page 112: The   UNIX   Operating   System

112

112

112

TCS ConfidentialTCS Confidential

* Developed by Bill Joy ( Berkeley University)

* More helpful interaction

* Permits shorthand repetition

* Permits aliasing

The C Shell

Page 113: The   UNIX   Operating   System

113

113

113

TCS ConfidentialTCS Confidential

The variables can be defined using a set for C-Shell variables

e.g., (on - C shell)

% set x=‘date‘% echo $x Wed Sep 23 12:15:20 EDT 1991

Page 114: The   UNIX   Operating   System

114

114

114

TCS ConfidentialTCS Confidential

History - Records previous commands ! is used to execute previous command

Command Format :! <event> [ <word> <modifier> ]

<event> - absolute !1- relative !-3- name !c expr !?su?

<word> - absolute 0, 1, ...n- range a - e- last $ - All arguments *

<modifier> - Substitute :s/trg1/trg

- Print only :s/trg1/trg/p

Page 115: The   UNIX   Operating   System

115

115

115

TCS ConfidentialTCS Confidential

History Mechanism

Keeps track of commands

% history Lists previous commands

% ^old^new Modify last command

e.g., % cd /usr/trg/SRC

% ^SRC^src

% cd /usr/trg/src

% !15 Run command 15

% !c Run previous command beginning with c

Page 116: The   UNIX   Operating   System

116

116

116

TCS ConfidentialTCS Confidential

Changing Commands

:S/pattern/replacement

e.g.,

% !cd:s/trg/trg1

cd /usr/trg1/src

% !ls : p Prints the previous command beginning with ls but does not execute it

Page 117: The   UNIX   Operating   System

117

117

117

TCS ConfidentialTCS Confidential

Using Arguments

!$ last argument

!^ Begin argument

!* All arguments

!10:5-9 Arguments 5 to 9 for command 10

e.g.,

%ls !15:2-4

Page 118: The   UNIX   Operating   System

118

118

118

TCS ConfidentialTCS Confidential

Alias mechanism

Short names for frequently-used long commands

e.g.,

% alias cdms ‘cd /usr/man/man\!$’% cdms 2% pwd

/usr/man/man2

% alias cd ‘cd \!*;set prompt=”`pwd`>”’sets the prompt to the present working directory as and when cd is used to change the working directory.

Page 119: The   UNIX   Operating   System

119

119

119

TCS ConfidentialTCS Confidential

{ } Attach filenames to common root

%cp /usr/trg4/{ac,docs,test} .

%cp/usr/trg4/ac .

%cp /usr/trg4/docs .

%cp /usr/trg4/test .

%ls {/usr/bin,/bin}/{ls,more}

/usr/bin/ls : not found

/bin/ls

/usr/bin/more

/bin/more : not found

Filename Grouping

Page 120: The   UNIX   Operating   System

120

120

120

TCS ConfidentialTCS Confidential

Using C - Shell e.g.,

% cc test.c% vi test.c% !c% a.out% !v% !c - o test% test% car /usr/trg2/document/report

% !! : s/car/cator

% ^car ^cat

Page 121: The   UNIX   Operating   System

121

121

121

TCS ConfidentialTCS Confidential

Variables in .cshrc of C SHELL

% set variable=value

histchars :% set histchars=";,"will thereafter use

; as execution character , as substitution characterhistory :% set history=40

path:% set path=:.:/bin:/usr/bin:

prompt :% set prompt=”\!>”

Page 122: The   UNIX   Operating   System

122

122

122

TCS ConfidentialTCS Confidential

Variables in .cshrc of C SHELL

setenv used to make a variable as an environment variable so that whenever changes are made it is also reflected in the environment like TERM , DISPLAY is used

% setenv TERM=AT386-M

filec : file name completion% set filec : Predefined Its usage : % set variable

% unset variable

ignoreeof : To ignore all eof character ^D% set ignoreeof

noclobber : Abandons all command using output redirection % set noclobber which destroys an existing file and appends to non-existing file

Page 123: The   UNIX   Operating   System

123

123

123

TCS ConfidentialTCS Confidential

TESTing Strings

test - z $string String length equal to zero

test - n $string String length not equal to zero

test $str1 = $str2 str1 is equal to str2

test $str1 != $str2 str1 is not equal to str2

test $string string is not a null string

Test Conditions

Page 124: The   UNIX   Operating   System

124

124

124

TCS ConfidentialTCS Confidential

To algebraically compare variable values

test $num1 -eq $num2

Other algebraic operators -ne, -gt -ge -lt, -le

File related

$ test -f file True if file exists and is an ordinary file

$ test -r file True if file exists and is readable file

$ test -w file True if file exists and is writable file

$ test -s file True if file exists and has size greater than zero

Page 125: The   UNIX   Operating   System

125

125

125

TCS ConfidentialTCS Confidential

Control flows

if command thencommands [ elif commands ] ...[ else commands ]fi

case word in,pattern) commands ;;pattern) commands ;;...esac

Shell Programming - The Bourne Shell

Page 126: The   UNIX   Operating   System

126

126

126

TCS ConfidentialTCS Confidential

for name [ in word ...]do

commands done

while commanddo

commands done

until commanddo

commands done

Page 127: The   UNIX   Operating   System

127

127

127

TCS ConfidentialTCS Confidential

break n exit from for / while / until from level n

continue n next iteration of for / while / until from level n

exit n exit with value

export [name..] export

test expr evaluate conditions

read [arg] read variables from stdin or Keyboard

shift n shift positioned parameters w.r.t $1

Page 128: The   UNIX   Operating   System

128

128

128

TCS ConfidentialTCS Confidential

Examples $ for i in *.dat> do > size=‘wc -c $i‘ > if test $size -eq 0> then> rm $i> fi> done

- 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

However, by mentioning #! /bin/sh or #! /bin/csh in the first line of the

shell program, it can be parsed to either Bourne shell or C-shell resp’ly

Page 129: The   UNIX   Operating   System

129

129

129

TCS ConfidentialTCS Confidential

Exampleecho If you have a TTY vt100 enter vt100echo If you have a TTY AT386-M enter AT386-Mecho If you have a TTY sma84 enter sma84read termcase $term in

vt1001) TERM=vt100;;

AT386-M) TERM=AT386-M;;

sma84) TERM=sma84;;

*) echo ‘Invalid TERM’;;

esac# Making it is an environment variableexport TERMecho end of program This can be a part of your .profile

Page 130: The   UNIX   Operating   System

130

130

130

TCS ConfidentialTCS Confidential

Control Flows

IF if (expr) thencommand;

[ else if ]command;

[ else ]command;

endif

SWITCH switch (string)

case string1:command;

breaksw

case string2:command;

breaksw

default :command;

breaksw

Page 131: The   UNIX   Operating   System

131

131

131

TCS ConfidentialTCS Confidential

FOREACH foreach name (word)

commands end

WHILE while ( expr ) commands

end

UNTIL until ( expr )commands

end

Page 132: The   UNIX   Operating   System

132

132

132

TCS ConfidentialTCS Confidential

Chapter 5Chapter 5

Advanced UtilitiesAdvanced Utilities

Page 133: The   UNIX   Operating   System

133

133

133

TCS ConfidentialTCS Confidential

1. Redirection2. Pipes3. Pipe fitting with tee utility4. Filters5. Find6. Sort7. Utilities that process tabular data-

cut, join, csplit 8. Ps and Kill9. 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 Make14. Lint15. Lex 16. Yacc

Advanced Utilities

Page 134: The   UNIX   Operating   System

134

134

134

TCS ConfidentialTCS Confidential

Redirection Metacharacter Performs

“<“ input

“>” output write

“>>” output append

e.g.,$ whotrg1 tty00 Apr 8 09:33trg2 tty02 Apr 8 11:10

$ who > who_out

$ cat who_outtrg1 tty00 Apr 8 09:33trg2 tty02 Apr 8 11:10

$ date > date_out

$ cat date_out Fri Apr 8 14 : 30 : 10 est 1983

$ who >> date_out$ cat date_outFri Apr 8 14 : 30 : 10 est 1983trg1 tty00 Apr 8 09:33trg2 tty02 Apr 8 11:10

Page 135: The   UNIX   Operating   System

135

135

135

TCS ConfidentialTCS Confidential

Metacharacter Performs

“|” piping

e.g.,

Without Pipe $ cat /etc/passwd > temp$ sort < temp$ rm temp

With Pipe $ cat /etc/passwd | sort

* No need for creation/deletion of a file

* Sorts the file passwd as per the first entry in passwd

Pipes :

Page 136: The   UNIX   Operating   System

136

136

136

TCS ConfidentialTCS Confidential

A UNIX Pipeline

Standard Input

>Prgm #1 Prgm #2 Prgm #3 Prgm #4

>Prgm #5 Prgm #6

Standard Output<

Page 137: The   UNIX   Operating   System

137

137

137

TCS ConfidentialTCS Confidential

Helps in creating the intermediate file during the pipe operation

e.g.,

$ ls *.c | tee Cflst | sort$ cat cflst

* Creates the intermediate file Cflst * Cflst contains the list of c files

The TEE Utility :

Page 138: The   UNIX   Operating   System

138

138

138

TCS ConfidentialTCS Confidential

grep get regular expressions only

fgrep fast, several simple strings at one time

egrep extended grep, can handle more powerful expressions like | - or operators

FILTERS :

Page 139: The   UNIX   Operating   System

139

139

139

TCS ConfidentialTCS Confidential

$ grep pattern filenames

Options :

-c number of lines matched

-i ignore case

-n print line with line-number

-v print lines which do not match

Page 140: The   UNIX   Operating   System

140

140

140

TCS ConfidentialTCS Confidential

Searching Files with grep

e.g.,

$ grep -ni func1 *.c Prints all the lines and line numbers in files *.c

that match pattern func1 ignoring the case

$ grep ‘*’ * Search for the pattern * in all the files

$ ls -l | grep ‘^d’ Searches for all subdirectories

Page 141: The   UNIX   Operating   System

141

141

141

TCS ConfidentialTCS Confidential

e.g.,

$ egrep ‘int|long’ test.c Searches for all those lines containing

either int or long in test.c

$ egrep ‘ (^[A-Z])’ testfile Searches for all the lines which start with a capital letter

$ cat exprfile Searches for lines having at least 3 commas ,.*,.*, in file testfile using the

exprfile

$ egrep -n -f exprfile testfile

Page 142: The   UNIX   Operating   System

142

142

142

TCS ConfidentialTCS Confidential

Find To locate one or more files

find path-list cond-list action-list

path-list one or more directory namescond-list -type x x can be d, f, or c

d directoryf ordinary filec character special file

-user name for a specificed user name

-group name for a specified group name

-size n File size n. blocksIf n follows c then so many characters

-links n locate for file with n links

-atime n files accessed during n days ago

-mtime n modified n days ago

-ctime n created n days ago

-perm nnn permission flags match nnn

-name fname with specified filenames

Page 143: The   UNIX   Operating   System

143

143

143

TCS ConfidentialTCS Confidential

actionlist

- print display path names

- exec command execute the unix command

- cpio device copy the files on the tape in specified format

- ok command like exec , but executed interactively

e.g.,find / -atime 7 -print - will print files accessed in

exactly 7 daysfind / -atime +7 -print - will print files accessed

earlier than 7 daysfind / -atime -7 -print - will print files accessed

within 7 days

Page 144: The   UNIX   Operating   System

144

144

144

TCS ConfidentialTCS Confidential

Examples

$ find / -atime +30 -print

$ find / -atime +30 -size +10 -print

$ find / -atime +30 -size +10 -ok rm -f {} \;

$ find . -perm 0777 -print

$ find . -perm 0777 -print -exec rm {} \;

$ find / -name passwd -print

- Will find the passwd file

Page 145: The   UNIX   Operating   System

145

145

145

TCS ConfidentialTCS Confidential

Sort* Sort keys can be fields or lines* A field is a string of characters separated by a field separator or new line.

$ sort {-options} {+post1} {-post2} {files}

The sort key begins at post1 ands ends just before post2. There can be several keys.

Options b ignore leading blanks and tabs

c only check if input file is already sorted

d dictionary order letters, digits, blanks

f ignore case

i ignore non-printable characters

n numeric sortingr reverse ordertp use p as separatoru output only lines with unique keyso filenameout save output in filenameout

Page 146: The   UNIX   Operating   System

146

146

146

TCS ConfidentialTCS Confidential

e.g.,

$ sort -t: +2n -3 /etc/passwd

Print the passwd file sorted by numeric user id

$ who | sort +4n

Sorts according to the login time stamp of the user

Page 147: The   UNIX   Operating   System

147

147

147

TCS ConfidentialTCS Confidential

uniq Finds and eliminates duplicate lines in a file and is often used with sort

$ sort <file> | uniq -c

Sorts and ouputs the number of count of lines containing unique fields

$ sort <file> | uniq -d

Gives only the duplicated lines

tsort Accepts as input a partial ordering and produces a fully ordered list of the items.

$ tsort psortfile

Page 148: The   UNIX   Operating   System

148

148

148

TCS ConfidentialTCS Confidential

Cut

* Deletes columns from a file producing a new file with shorter lines

* Cuts out selected fields of each line in a file.

* Cuts columns from a table or fields from a file which can be of type

- Fixed length fields or- Delimited by some character

Processing Tabular Data

Page 149: The   UNIX   Operating   System

149

149

149

TCS ConfidentialTCS Confidential

Cut (contd.)

cut -c list { file1 file2 ...}

e.g.,

cut -c 5-70 file1

cut would pass 5-70 characters from file1

cut -flist {-d char } {file1 file2....}

e.g.,

who | cut -d” “ -f1

gives a list of user login names

cut -d: -f 1,5 /etc/passwd

gives a list of user ID and names

Page 150: The   UNIX   Operating   System

150

150

150

TCS ConfidentialTCS Confidential

JOIN

* Combines corresponding lines in two files by relating the contents of one or more columns.

* Implements a relational data base ‘join’ on two tabular files

-jn m join on the mth field of file ‘n’

-on.m output mth field of nth filen - file no. m - field no.

-tc use char c’ as separator

Page 151: The   UNIX   Operating   System

151

151

151

TCS ConfidentialTCS Confidential

e.g.,

$ join -j1 4 -j2 3 -o 1.1 2.1 1.6 -t: etc/passwd etc/group

- joins field group id

- outputs the following parameters

login group loginname name dir

Page 152: The   UNIX   Operating   System

152

152

152

TCS ConfidentialTCS Confidential

csplit context split

$ csplit [-k] [-f prefix] [-s] file name arg1 [..argn]

Reads file and separates it into n+1 section defined by arg1...argn

Options :

-s Normally csplit prints the character counts for each file , -s is to suppress this

-k csplit removes previously created files in case of error , -k is to avoid this

csplit normally creates file as xx00 , xx01 ... , xx99

-f prefix creates file with that prefix instead of default xx

Page 153: The   UNIX   Operating   System

153

153

153

TCS ConfidentialTCS Confidential

csplit(contd.)

e.g.,

$ csplit -f cobol inpfile /Procedure division/’ / Para5./ /Para6./ /Para 7./

* Creates file as cobol 00 .. cobol 03* Edit these Cobol files* Can be recombined as

$ cat cobol 0[0-3] > file

csplit -k prog.c ‘%main(%’ ‘/^}/+1’ {20}

* Breaks file prog.c containing C routineupto a maximum of 21

* ‘% expr %’ —> no. file is created for this section

* No csplit for the main routine ‘%main%’

Page 154: The   UNIX   Operating   System

154

154

154

TCS ConfidentialTCS Confidential

PS, kill

$ somecommand &

5511 - pid

$ps

pid tty time command

3432 2 0 : 24 -sh5765 2 0 : 03 ps5511 2 0 : 51 somecommand

$ kill 5511$ pspid tty time command

3432 2 0 : 24 -sh5985 2 0 : 03 ps

Page 155: The   UNIX   Operating   System

155

155

155

TCS ConfidentialTCS Confidential

$ stubborn-cmd &

pid tty time command3432 2 0 : 24 -sh6004 2 0 : 03 ps5995 2 0 : 44 stubborn-cmd

$ kill 5995

$ ps pid tty time command3432 2 0 : 24 -sh6004 2 0 : 03 ps5995 2 0 : 44 stubborn-cmd

$ kill -9 5995

$ pspid tty time command3432 2 0 : 24 -sh6103 2 0 : 03 ps

Page 156: The   UNIX   Operating   System

156

156

156

TCS ConfidentialTCS Confidential

time Time a command

$ time wc test.c > wc.test real 2.0user 0.4sys 0.3

nohup Protecting a process from hanging and quit signals or interrupts

The standard output is sent to nohup.oute.g.,

$ nohup du / & 820 Sending output to nohup.out $ logout

Timely Execution :

Page 157: The   UNIX   Operating   System

157

157

157

TCS ConfidentialTCS Confidential

nice * Executes at specified priority* Default priority is 24

$ nice +n Raise priority

$ nice -n Lower priority

$ nice n set priority

at Executes process at specified time

$ at 5 pm echo ^G ^G Time to logoff >/dev/tty04 ^D

$

Page 158: The   UNIX   Operating   System

158

158

158

TCS ConfidentialTCS Confidential

tar tape archiver

Copies files on backup medium such as floppy or tape in tar format

tar [options] devicename filelist

Options :

c create a new tape backup tape old files are overwrittenr append files to the tape

t list the names of files from backup tapex extract files from the backup medium

u update a tape, if the named files are not present or have been modified later on

v verbose ; provides informational messages, such as the name of each file as and when it is

encountered

f devicename use device for backup medium

User Backup Utilities :

Page 159: The   UNIX   Operating   System

159

159

159

TCS ConfidentialTCS Confidential

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

Creates necessary directories

tar xvf /dev/fd096 try.c Extracts the file try.c from /dev/fd096

tar tvf /dev/fd096 Generates a file list of /dev/fd096

find / -mtime -7 -exec tar uf /dev/fd096 {} \; All the files modified last week is backed up onto /dev/fd096

Page 160: The   UNIX   Operating   System

160

160

160

TCS ConfidentialTCS Confidential

cpio * Copy files archives in and out* Bundles all the files into one package

cpio [options] file list devicename Options

-o Copy these files onto tap

-i Extract files from tape

-p Read a list of file or path names from the standard input

-v display a verbose set of cpio action

-c character information in ASCII for portability considerations

-t For listing files from the backup medium

-O Append files to the end of tape to be used with -A

-d Creates necessary directories

-k In case of error , ignore the error and continue

Page 161: The   UNIX   Operating   System

161

161

161

TCS ConfidentialTCS Confidential

cpio (Examples)

$ ls *.c | cpio -ocBv > /dev/rmt/0n

Lists the files *.c and copy onto the device /dev/rmt/0n

$ cpio -ocBv < filelst > /dev/rct/c0s0

Copies all the files mentioned in filelst onto the catridge tape

$ cpio -icBdv < /dev/rct/c0s0

Extracts all the files from device c0s0 and creates necessary required directories

$ cpio -itv < /dev/rmt/0m

List the files from the tape /dev/rmt/0m

Page 162: The   UNIX   Operating   System

162

162

162

TCS ConfidentialTCS Confidential

dd convert, reblock, translate, copy a tape file.

dd {option = value }

Options Values

if input file nameof output file nameibs input block size (Default 512)obs output block size(Default 512)cbs conversion block sizeskip n records before copying from I/P fileseek write after n output records in O/P filecount n records conv To ASCII, EBCDIC, lcase, ucase (separated by

a comma)e.g., $ dd if=/dev/rmt/0n of=x ibs=800 cbs=80 conv=ascii,lcase

Page 163: The   UNIX   Operating   System

163

163

163

TCS ConfidentialTCS Confidential

doscp Copy a UNIX file in DOS format orCopy a DOS file in UNIX format

doscp source file target file

e.g.,

$ doscp /usr/trg/test.c a: copies the file test.c onto the floppy

$ doscp a:try.c . copies the file try.c from the floppy onto

the current working directory

Page 164: The   UNIX   Operating   System

164

164

164

TCS ConfidentialTCS Confidential

pr prepares a file for printing

Options

-k K col. Output

+k from page k

-lk set length of page to k lines

-p pause after each page

-h take next argument as header

-wk set width to k characters

-d double space

e.g.,

$ pr -3 d h “file list” f1 f2- Generates a header as file list- 3 Column output- Double spacing

$ pr -5 wordlist - Generates 5 column output

Output Related Commands :

Page 165: The   UNIX   Operating   System

165

165

165

TCS ConfidentialTCS Confidential

pr (contd.)

$ pr myfileprepare myfilenov 24 : 11 : 31 1987 myfile page 1

$ pr -t myfile suppresses the header

This file can be printed using$ pr myfile | lpr

Page 166: The   UNIX   Operating   System

166

166

166

TCS ConfidentialTCS Confidential

lpr Print a file on the line printer

$ lpr myfile prints myfile on the printer

$ lpr -c myfile make a copy to the spool directory

$ lpr -r myfile myfile is removed from the spool

lp Combines the actions of pr and lpr

$ lp myfile prints myfile with header, date, time and page numbering.

Page 167: The   UNIX   Operating   System

167

167

167

TCS ConfidentialTCS Confidential

sleep Suspend execution

$ sleep 5 prompt appears after 5 seconds

$ sync * updates super block* writes all disc buffers* calls sync before stopping system to

ensure file system integrity* saves all modifications

$ wait waits till all background jobs are over$du determines disk usage

-s total blocks -a size of each file

Other Utilities

Page 168: The   UNIX   Operating   System

168

168

168

TCS ConfidentialTCS Confidential

df displays no. of free blocksdf [option] file system

clear clears the screen and the prompt goes to

top of screen

tr replaces specified characters with other characters

e.g.,$ tr “[a-z]” “[A-Z]” < lfile > ufileReplaces all small case letters to upper case letters

$ tr -d’ ‘ < tstfl > tstfl2Deletes all the blank characters

$ tr -s ‘\012’ < try > try2Removes adjacent blank lines in file try

Page 169: The   UNIX   Operating   System

169

169

169

TCS ConfidentialTCS Confidential

Making & Maintaining large programs

What is make? Program for maintaining large number of programs

Need for make * Difficulties in remembering the dependencies

* Simple mechanism for maintaining an up-to-date version of Programs

Characteristics * Helps maintain large systems

* Specifies dependencies of files in the system and t the actions to make them

* Uses creation date to determine the actions to be taken

make - An Introduction

Page 170: The   UNIX   Operating   System

170

170

170

TCS ConfidentialTCS Confidential

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- how to regenerate the program system

Example :

final

mod1 mod2 mod3

Page 171: The   UNIX   Operating   System

171

171

171

TCS ConfidentialTCS Confidential

make : AN INTRODUCTION …Contd...

Example (contd):

Makefile or makefile

final : mod1.o mod2.o mod3.o cc -o final mod1.o mod2.o mod3.o

mod1.o : mod1.ccc -c mod1.c

mod2.o : mod1.ccc -c mod2.c

mod3.o : mod3.ccc -c mod3.c

Run the command as ....

$ make final

use -f urflname option If the name of the file is not Makefile or makefile

Page 172: The   UNIX   Operating   System

172

172

172

TCS ConfidentialTCS Confidential

Using the Macro facility and Inference rules

QSRC = qp1.c qp2.c qp3.cINCLUDES = lim.h com.hOBJECTIF = qp.o qex.o libs.a

query : $(OBJECTIF) cc -o query $ (OBJECTIF)

qp.o : $ (QSRC)cc -o qp.o $ (QSRC)

libs.a : libs(lib1.o) libs(lib2.o)qex.o lib1.o lib2.o : $ (INCLUDES)LIBES = libs(libs1.o) libs(libs2.o)prog : $(OBJECTIF) cc $(OBJECTIF) $(LIBES) -o prog

Page 173: The   UNIX   Operating   System

173

173

173

TCS ConfidentialTCS Confidential

* Reports the various inconsistencies that can exist in a program in the

following areas . Syntax errors. Unused variables. Unused arguments. Unused functions. Unused return values. Unused external variables. Unintialized variables. Type checking features. Portability considerations. Statement not reached. Excludes goto statements

* Invoked aslint [options] filename

Lint - C Program Checker

Page 174: The   UNIX   Operating   System

174

174

174

TCS ConfidentialTCS Confidential

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];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);}

Page 175: The   UNIX   Operating   System

175

175

175

TCS ConfidentialTCS Confidential

Lint - C Program Checker …Contd...

Generate an output after invoking lint as lint test.c -lm

test.c warning : k , l unused in function main

warning : j may be used before set

warning : main() returns random to invocation environment

Function argument (number) type inconsistencyscanf (arg2) int :: format int * : test.c

Value type declared inconsistentlysqrt llib-lm : test.c

Function argument ( number ) used inconsistently sqrt ( arg1 ) : test.c

Function called with variable number of argumentsadd : test.c

Function returns value which is always ignoredprintf scanf

Page 176: The   UNIX   Operating   System

176

176

176

TCS ConfidentialTCS Confidential

source * General tool for separating character strings patterns in an input

* String patterns can be specified using rules

syntax definitions

% %

rules

% %

user subroutines

Lex

Page 177: The   UNIX   Operating   System

177

177

177

TCS ConfidentialTCS Confidential

Lex …Contd...

Example (on rule)

Expression ——> integer * integer

Expression ——> integer + integer

Expression ——> integer - integer

Expression ——> integer / integer

The lex specification file

%%[0-9]+ { return (INT); }[-*+/] { return (OPR); }[\t ] ;

{printf(“Lexical analyser error\n”);exit(-1);}

Page 178: The   UNIX   Operating   System

178

178

178

TCS ConfidentialTCS Confidential

Lex …Contd...

%%yywrap(){return(1);}

yywrap() indicates no further input available

Invoked as

$ lex filename$ lex lex.l

Generates

lex.yy.c

Page 179: The   UNIX   Operating   System

179

179

179

TCS ConfidentialTCS Confidential

What is it? Yet Another Compiler Compiler

Features * General tool describing input to a program

* Specify input structure

* Code for each structure

* Outputs a subroutine which handles the input

* User supplied routine to supply next basic item

Yacc :

Page 180: The   UNIX   Operating   System

180

180

180

TCS ConfidentialTCS Confidential

Yacc …Contd...

Specifications Declarations

%%rules%%

Example

%token INT OPR%start expr %%expr : INT OPR INT{printf(“The input expression is correct\n”);}| error{printf (“The input expression is wrong \n”);}%%

Invoked as $ yacc filename$ yacc yac.y

Generates y.tab.c

Page 181: The   UNIX   Operating   System

181

181

181

TCS ConfidentialTCS Confidential

Consider this program...

#include <stdio.h>main()

{yyparse(); }

#include “y.tab.c”#include “lex.yy.c”

The whole program can be compiled as ...

$ cc main.c -ll -ly-ll and -ly to link lex and yacc library$ a.out

A Program using both lex & yacc

Page 182: The   UNIX   Operating   System

182

182

182

TCS ConfidentialTCS Confidential

Chapter 6Chapter 6

Communication Features Communication Features

Page 183: The   UNIX   Operating   System

183

183

183

TCS ConfidentialTCS Confidential

1. User communication commandsmailwritetalkpostnewsmesg

2. Networking commandsuucpuutorlogintelnetftprcpuuxctcu

Communication Features

Page 184: The   UNIX   Operating   System

184

184

184

TCS ConfidentialTCS Confidential

* Mail

* Write

* Talk

* Post

* News

* Mesg

User Communication Commands :

Page 185: The   UNIX   Operating   System

185

185

185

TCS ConfidentialTCS Confidential

Mail Sends and receives mail messages between users

Sending mail on local system

At the end of the message press ^D to exit

$ mail <loginnames>

Example : (Assume the current user is trg)

$ mail trg1

Sending mail on remote system

$ mail recipient@remote_system.domain_info

Page 186: The   UNIX   Operating   System

186

186

186

TCS ConfidentialTCS Confidential

Receiving mail

$ mail Shows the message received

? Promptq quits [file] save (defalut mbox)w [file] write without headerd deleten or + next message- previousr reply to the senderm [user] mail to user! cmd run the shell command

* The message could be saved or deleted

* Environment could be setup in .mailrc

Page 187: The   UNIX   Operating   System

187

187

187

TCS ConfidentialTCS Confidential

User Communication commands …Contd...

Write Allows sending messages to a user terminal from

another terminal

The message is ended by pressing ^D.

$ write <username>

Talk Allows interactive dialogue between users at two

different terminals.

$ talk <username>

Page 188: The   UNIX   Operating   System

188

188

188

TCS ConfidentialTCS Confidential

Post Messages can be posted on a “bulletin board” for previewing by all users.

News * Keeps the user informed of current events* Refers file /usr/news

e.g., $ news Prints all the news , latest first

$ news reorg Prints the news named reorg

mesg The terminal can be write protected to prevent other users from

writing onto your terminal

e.g., $ mesg [option]option :- y write allowed

- n remove write permission on the terminal

$ mesg prints the current status whether mesg is y or n

Page 189: The   UNIX   Operating   System

189

189

189

TCS ConfidentialTCS Confidential

* uucp

* uuto

* telnet

* rlogin

* ftp

* rcp

* uux

* ct

* cu

Networking Commands

Page 190: The   UNIX   Operating   System

190

190

190

TCS ConfidentialTCS Confidential

uucp * allows copying files from one unix system to

another* Refers file uuname and uulog

uucp [options] source-files destination files

options -d make necessary directory-c do not copy local file to spool directory-m send mail to the requester when the copy is completed

$ uucp -d -m file? sys_2!/usr/spool/uucppublic

Copies the files file? creating appropriate directories onto system sys_2 onto

/usr/spool/uucppublic

Page 191: The   UNIX   Operating   System

191

191

191

TCS ConfidentialTCS Confidential

uuto * Simplified version of uucp* Sends file to /usr/spool/uucppublic

$ uuto filename(s) system!login

$ uuto -m test.c sys2!trg2

Sends a mail to the sender when the job is over

rlogin * Allows remote login over the network * Similar to telnet, but a much more flexible

facility.$ rlogin system_name!username

Page 192: The   UNIX   Operating   System

192

192

192

TCS ConfidentialTCS Confidential

Networking Commands …Contd...

ftp * File transfer protocol* Transfers files from one system to another

$ ftp

ftp > open sys1 Name login:passwd

ftp > ? Gives you the help

ftp > get filename Gets the file onto the current system

ftp > put filename Puts the file onto the \sys1

ftp > close $

Page 193: The   UNIX   Operating   System

193

193

193

TCS ConfidentialTCS Confidential

rcp Similar to ftp, but a much more flexible facility

uux * Unix to Unix command execution on remote

systems* Gather files from various computers, run a command on a specified computer and

redirect the stdout to a file on a specified computer

$ uux [options] commandstring All shell special characters must be quoted

$ pr minutes | uux -p host!lp

Command line queues the file minutes to be printed on the area of the computer host

Page 194: The   UNIX   Operating   System

194

194

194

TCS ConfidentialTCS Confidential

ct * Connect terminal to remote terminal* Connects your terminal to remote

terminal which is equipped with a modem

This command dials the phone number of the modem

$ ct [options] telno

$ ct -h -w5 -s1200 9=5553497

ct will call modem using a dialer operating at a speed of 1200 baud , wait for 5 minutes before quitting if dialer is not

available and use the -h option not to disconnect the local terminal

Page 195: The   UNIX   Operating   System

195

195

195

TCS ConfidentialTCS Confidential

cu * connects local system to remote system* allows you to be logged on to both

simultaneously

Examples cu -s2400 9=5557867 Connected

login :

~%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

~%$command run the command on local and send the output to the remote terminal

~ % . terminate the link

Page 196: The   UNIX   Operating   System

196

196

196

TCS ConfidentialTCS Confidential

Chapter 7Chapter 7

System callsSystem calls

Page 197: The   UNIX   Operating   System

197

197

197

TCS ConfidentialTCS Confidential

1. Introduction

2. File related system callsopen()read()write()creat()chmod()chown()lseek()

3. Process related system callsfork()getpid(), getppid(), getpgrp()wait()execl()

System Calls :

Page 198: The   UNIX   Operating   System

198

198

198

TCS ConfidentialTCS Confidential

* 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

* 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

Page 199: The   UNIX   Operating   System

199

199

199

TCS ConfidentialTCS Confidential

Basic tasks in file operations

- opening files- reading files- writing in files- creating files- changing the permission of files - changing the owner and group of files- seeking to file-location - closing files

Page 200: The   UNIX   Operating   System

200

200

200

TCS ConfidentialTCS Confidential

open () * open() an existing file

int open (filename,mode)char *filename;int mode;

filename - character pointer to the name of the file

mode - integer signifying the mode0 for read1 for write2 for read and write

open() returns the file descriptors on success and returns -1 on error

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);

}

Page 201: The   UNIX   Operating   System

201

201

201

TCS ConfidentialTCS Confidential

read () * File should be opened in read mode

* read() an opened fileint read (filedesc,buffer,nbytes)

int filedesc;char *buffer;int nbytes;

filedesc - File descriptor indicating which file to be read

buffer - An area of buffer storage for holding the Characters read

nbytes - number of characters to be read at a time

read() returns the number of characters read and 0 in case ofend of file (EOF) and returns -1 on error

Page 202: The   UNIX   Operating   System

202

202

202

TCS ConfidentialTCS Confidential

Example :

Reading the file “test” 100 characters at a time

while ( ( n = read(fd,buff,100)) > 0 ){

printf(“file test has contents %s “,buff);}if ( n == 0 )

printf ( “ End of file “);

if ( n == -1 )printf (“Error in reading file test”);

When each read is finished the pointer advances by 100 bytes so that the next read picks from there

* If the number of characters left are less than nbytes ( in this example - 100 ) then read() will pick up what is left over

Page 203: The   UNIX   Operating   System

203

203

203

TCS ConfidentialTCS Confidential

write ()

* File should be opened in write mode

* write() to an opened file

int write (filedesc, buffer, nbytes)

int filedesc;char *buffer;int nbytes;

filedesc - File descriptor indicating which file to be written

buffer - The function takes from buffer and writes them to indicated file

nbytes - number of characters to be written at a time

write() returns the number of characters written and returns -1 on error

Page 204: The   UNIX   Operating   System

204

204

204

TCS ConfidentialTCS Confidential

Example :

while ( ( n = read (fd,buff,100)) > 0 ){

n1 = write (1,buff,100);/* writing to standard output *//* file id - 1 is for stdout */

if ( n1 == -1 )printf (“Error in writing on stdout");

}

if ( n == -1 )

printf (“Error in reading file test ");

Page 205: The   UNIX   Operating   System

205

205

205

TCS ConfidentialTCS Confidential

creat ()

* creat() creates a new file or overwrites on the existing file

int creat(filename, mode)char *filename;int mode;

filename - character pointer to the name of the file

mode - Integer signifying the modeThe mode is specified in octal code

creat returns the file descriptor on success and returns -1 on error

Page 206: The   UNIX   Operating   System

206

206

206

TCS ConfidentialTCS Confidential

creat () …Contd...

Example :

umask(0000);

fd = creat(“newfile”,0666);

if ( fd == -1 ){

printf(“error in creating file 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

Page 207: The   UNIX   Operating   System

207

207

207

TCS ConfidentialTCS Confidential

chmod ()

* chmod() set permissions for the file

int chmod (filename, mode)char *filename;int mode;

filename - character pointer to the name of the file

mode - Integer signifying the modeThe mode is specified in octal code

chmod() returns 0 on success

and returns -1 on error

Page 208: The   UNIX   Operating   System

208

208

208

TCS ConfidentialTCS Confidential

Example :

ret = chmod(“test.c”,0600);

if ( ret == -1 ){

printf(“error in changing the file permission”);

}

Changes the permission of file test.c i.e., read and write permissions for owner

Page 209: The   UNIX   Operating   System

209

209

209

TCS ConfidentialTCS Confidential

chown ()

* System call chown()

* chown() set ownership for the file

int chown (filename,owner ,group)char *filename;int owner , group ;

filename - character pointer to the name of the fileowner - owner id

group - group idchown() returns 0 on success and returns -1 on error

Page 210: The   UNIX   Operating   System

210

210

210

TCS ConfidentialTCS Confidential

chown () …Contd….

Example :

ret = chown(“test.c”,0,1);

if ( ret == -1 ){

printf(“error in changing the owner and group of the file”);

}Changes the owner and group of the file test.c as root and others respectively

Page 211: The   UNIX   Operating   System

211

211

211

TCS ConfidentialTCS Confidential

lseek ()

* lseek() changes the position of read-write pointer for the file descriptor

int lseek(filedes, offset, origin);int filedes, origin;long offset;

lseek() returns new-value of the pointer on successreturns -1 on error

The value of the pointer depends on origin :0 set the pointer to offset bytes from the begining of the file1 increment the current value of the pointer by offset2 set the pointer to the size of the file plus offset bytes

Page 212: The   UNIX   Operating   System

212

212

212

TCS ConfidentialTCS Confidential

lseek () …Contd...

Example :

ret = lseek(fd,1000,0);

if ( ret == -1 )

{

printf(“error in seeking to the 1000’th byte of the file “);

}

lseek(fd,1000,0) skips the first 1000 bytes of the file and starts reading from the 1001’th byte

Page 213: The   UNIX   Operating   System

213

213

213

TCS ConfidentialTCS Confidential

fork ()

* fork() creates a new process which is a child process

* Child process is a logical copy of the parent process

* Parent’s return value is the process id of the child

* Child’s return value is 0

Page 214: The   UNIX   Operating   System

214

214

214

TCS ConfidentialTCS Confidential

getpid () getppid () getpgrp ()

* getpid() returns the process id of the calling process

* getppid() returns the parent process id of the calling process

* getpgrp() returns the process group of the calling process

Page 215: The   UNIX   Operating   System

215

215

215

TCS ConfidentialTCS Confidential

EXAMPLE fork () , getpid () , getppid (), getpgrp ()

#include <stdio.h>main(){ int id ; int pid , pgrp ; int ppid ; id = fork(); printf (“PPID - %d PID- %d id - %d \n”, getppid() , getpid() ,id ); printf (“PGRP - %d \n “, getpgrp() );}

Page 216: The   UNIX   Operating   System

216

216

216

TCS ConfidentialTCS Confidential

EXAMPLE fork () , getpid () , getppid (), getpgrp ()

Output

PPID - 371 PID - 372 id - 0 - From child ProcessPGRP - 136

PPID - 136 PID - 371 id - 372 - From Parent ProcessPGRP - 136

PID - Process-ID

PPID - Parent Process - ID

ID - Returned value from fork()

PGRP - Process-group-ID

If PID is equal to the process PGRP then the process is the group leader

Page 217: The   UNIX   Operating   System

217

217

217

TCS ConfidentialTCS Confidential

wait () & execl ()

* wait() causes a parent to stop running and await the termination of a child process

* execl() overlays the original process with a new set of instructions

Example on execl()#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);

}printf(“ Parent process again \n”);

}

Page 218: The   UNIX   Operating   System

218

218

218

TCS ConfidentialTCS Confidential

EXAMPLE ON execl()

Output

Parent ProcessStatement from child processParent process againTue 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

The example on execl() gets modified as

#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”);

}

Page 219: The   UNIX   Operating   System

219

219

219

TCS ConfidentialTCS Confidential

OUTPUT OF THE MODIFIED EXAMPLE

Parent Process

Statement from child process

waits for the

child to finish

Tue Sep 10 11:34:17 1991

Parent Process again

Page 220: The   UNIX   Operating   System

220

220

220

TCS ConfidentialTCS Confidential