Introduction to UNIX

171
UNIX Intro. Introduction to UNIX Introduction to UNIX Objectives Objectives Motivate the use of UNIX Motivate the use of UNIX Introduce basic UNIX features Introduce basic UNIX features (e.g. using directories, files) (e.g. using directories, files) Introduce Introduce vi vi March 1997

Transcript of Introduction to UNIX

Page 1: Introduction to UNIX

UNIX Intro. 1

Introduction to UNIXIntroduction to UNIX

ObjectivesObjectives– Motivate the use of UNIXMotivate the use of UNIX– Introduce basic UNIX featuresIntroduce basic UNIX features

(e.g. using directories, files)(e.g. using directories, files)– Introduce Introduce vivi

March 1997

Page 2: Introduction to UNIX

UNIX Intro. 2

ContentsContents

1. 1. Background on UNIXBackground on UNIX

2. 2. Starting / FinishingStarting / Finishing

3. 3. Typing UNIX CommandsTyping UNIX Commands

4. 4. Commands to Use Right AwayCommands to Use Right Away

5. 5. UNIX helpUNIX help

continued

Page 3: Introduction to UNIX

UNIX Intro. 3

6.6. The UNIX File SystemThe UNIX File System

7. 7. Working with DirectoriesWorking with Directories

8. 8. Working with FilesWorking with Files99.. vivi

Page 4: Introduction to UNIX

UNIX Intro. 4

1. Background on UNIX1. Background on UNIX

1.1. 1.1. What is UNIX?What is UNIX?

1.2. 1.2. HistoryHistory

1.3. 1.3. Why use UNIX?Why use UNIX?

Page 5: Introduction to UNIX

UNIX Intro. 5

•1.1. What is UNIX?1.1. What is UNIX?

The UNIX Operating System (OS) is a The UNIX Operating System (OS) is a large program (mostly coded in C) that large program (mostly coded in C) that turns the computer into a useable machine.turns the computer into a useable machine.

It provides a number of facilities:It provides a number of facilities:– management of hardware resourcesmanagement of hardware resources– directory and file systemdirectory and file system– loading / execution / suspension of programsloading / execution / suspension of programs

Page 6: Introduction to UNIX

UNIX Intro. 6

1.2. (Brief) History1.2. (Brief) History

1969 1969 First UNIX at Bell LabsFirst UNIX at Bell Labs 19751975 Bell Labs makes UNIX freewareBell Labs makes UNIX freeware 1970’s1970’s Berkeley UNIX (BSD)Berkeley UNIX (BSD) 1980’s1980’s TCP/IPTCP/IP

MIT X-WindowsMIT X-Windows 1990’s1990’s The Web,The Web,

LINUXLINUX

Page 7: Introduction to UNIX

UNIX Intro. 7

1.3. Why Use UNIX?1.3. Why Use UNIX?

multi-tasking / multi-usermulti-tasking / multi-user lots of softwarelots of software networking capabilitynetworking capability graphical (with command line)graphical (with command line) easy to program easy to program portable (PCs, mainframes, portable (PCs, mainframes,

super-computers)super-computers)continued

Page 8: Introduction to UNIX

UNIX Intro. 8

free! (LINUX, FreeBSD, GNU)free! (LINUX, FreeBSD, GNU) popularpopular profitableprofitable

1996 Sales: US$34.5 Billion, up 12%1996 Sales: US$34.5 Billion, up 12% not tied to one companynot tied to one company active communityactive community

Page 9: Introduction to UNIX

UNIX Intro. 9

2. Starting / Finishing2. Starting / Finishing

2.1. 2.1. Your AccountYour Account

2.2. 2.2. Login to your AccountLogin to your Account

2.3. 2.3. Password TipsPassword Tips

2.4. 2.4. Logout from your AccountLogout from your Account

Page 10: Introduction to UNIX

UNIX Intro. 10

2.1. Your Account2.1. Your Account

Each user has their own space on Each user has their own space on fivedotsfivedots, , called their called their account.account.

Type your login ID and password to enter Type your login ID and password to enter your account.your account.

Only if the login ID and password match Only if the login ID and password match will you be let in.will you be let in.

Page 11: Introduction to UNIX

UNIX Intro. 11

2.2. Login to your Account2.2. Login to your Account

login: login: adad You type your ID and You type your ID and RETURNRETURN..

Password:Password: You type your password and You type your password and RETURNRETURN. It does not appear.. It does not appear.

$$ The UNIX prompt (or similar). The UNIX prompt (or similar). You can now enter commands.You can now enter commands.

Page 12: Introduction to UNIX

UNIX Intro. 12

2.3. Password Tips2.3. Password Tips

NEVERNEVER tell anyone your password. tell anyone your password. Don’t write it down.Don’t write it down. A good password is:A good password is:

– 8 (or more) characters long8 (or more) characters long– uses a mix of uppercase and lowercase letters, uses a mix of uppercase and lowercase letters,

numbers, and symbols (e.g. #, %).numbers, and symbols (e.g. #, %). You can change your password with the You can change your password with the passwdpasswd command (see later).command (see later).

Page 13: Introduction to UNIX

UNIX Intro. 13

2.4. Logout from your Account2.4. Logout from your Account

logoutlogout

oror

^D^D Press Press CONTROL CONTROL and and DD togethertogether

ororexitexit

Page 14: Introduction to UNIX

UNIX Intro. 14

3. Typing UNIX Commands3. Typing UNIX Commands

3.1. 3.1. The ShellThe Shell

3.2.3.2. Typing CommandsTyping Commands

3.3. 3.3. Control CharactersControl Characters

3.4.3.4. Changing your PasswordChanging your Password

Page 15: Introduction to UNIX

UNIX Intro. 15

3.1. The Shell3.1. The Shell

The UNIX user interface is called the The UNIX user interface is called the shellshell.. The shell does 4 jobs repeatedly:The shell does 4 jobs repeatedly:

displayprompt

executecommand

processcommand

readcommand the shell

Page 16: Introduction to UNIX

UNIX Intro. 16

3.2. Typing Commands3.2. Typing Commands

Try these:Try these:datedate

cal 3 1997cal 3 1997

whowho

ls -als -a

man calman cal Press spacebar to continue; Press spacebar to continue; ^C (^C (CONTROL CONTROL and C) and C)

to stopto stopclearclear

Page 17: Introduction to UNIX

UNIX Intro. 17

3.3. Control Characters3.3. Control Characters

Erasing charactersErasing charactersDELETEDELETE delete last characterdelete last character

^H^H delete last characterdelete last character(press (press CONTROL CONTROL and H and H

together).together).

^W^W delete last worddelete last word

^U^U delete the linedelete the line

Page 18: Introduction to UNIX

UNIX Intro. 18

Very useful control charactersVery useful control characters

^C^C terminate commandterminate command

^S^S suspend outputsuspend output

^Q^Q resume outputresume output

Page 19: Introduction to UNIX

UNIX Intro. 19

Special Characters can be AlteredSpecial Characters can be Altered

Show current settings:Show current settings:stty -allstty -all

Change a setting:Change a setting:stty erase ^?stty erase ^? Type Type ^̂ and and ??. .

Reset:Reset:stty sanestty sane

Page 20: Introduction to UNIX

UNIX Intro. 20

3.4. Changing your Password3.4. Changing your Password

The command is:The command is:passwdpasswd

It will ask you for the new password twice.It will ask you for the new password twice.

Page 21: Introduction to UNIX

UNIX Intro. 21

4. Command to Use Right Away4. Command to Use Right Away

4.1. 4.1. Date CommandsDate Commands

4.2. 4.2. You and the SystemYou and the System

4.3. 4.3. CalculatorsCalculators

4.4. 4.4. GamesGames

Page 22: Introduction to UNIX

UNIX Intro. 22

4.1. Date Commands4.1. Date Commands

datedate Gives time and dateGives time and date

calcal CalendarCalendarcal 1997cal 1997

cal 3cal 3

cal 7 1962cal 7 1962

cal 9 1752cal 9 1752 Not a mistake. Why?Not a mistake. Why?

Page 23: Introduction to UNIX

UNIX Intro. 23

4.2. You and the System4.2. You and the System

uptimeuptime Machine’s ‘up’ timeMachine’s ‘up’ time hostnamehostname Name of the machineName of the machine

whoamiwhoami Your nameYour name quotaquota Your quotasYour quotas

quota -vquota -v

Page 24: Introduction to UNIX

UNIX Intro. 24

4.3. Calculators4.3. Calculators

xcalcxcalc Requires X-WindowsRequires X-Windows

expr expr ee Simple arithmeticSimple arithmeticexpr 3 + 5 + 7expr 3 + 5 + 7

bcbc Programmable Programmable Calculator Calculator

Page 25: Introduction to UNIX

UNIX Intro. 25

Using bcUsing bc

bcbc3 + 5 + 73 + 5 + 7

1717 OutputOutput^D^D

bc -lbc -l Use Maths libraryUse Maths libraryscale=3scale=3 Set display to 3 dpSet display to 3 dp150/60150/60l(30)l(30) natural log functionnatural log function^D^D

Page 26: Introduction to UNIX

UNIX Intro. 26

bcbcobase=2obase=2 Output baseOutput baseibase=16ibase=16 Input baseInput baseFFC1FFC1^D^D

Page 27: Introduction to UNIX

UNIX Intro. 27

5. UNIX Help5. UNIX Help

5.1. 5.1. On-line HelpOn-line Help

5.2. 5.2. UNIX booksUNIX books

Page 28: Introduction to UNIX

UNIX Intro. 28

5.1. On-line Help5.1. On-line Help

manman Manual pagesManual pages Spacebar to go on; Spacebar to go on; ^C ^C to stopto stop

man gnuchessman gnuchess

man manman man

apropos apropos topictopic Lists commands Lists commands related to related to topictopic

apropos gameapropos game

apropos helpapropos help

Page 29: Introduction to UNIX

UNIX Intro. 29

man -k man -k topictopic Same as Same as aproposapropos

whatis whatis cmdcmd One-line descriptionOne-line descriptionwhatis nethackwhatis nethack

where where cmdcmd Location of Location of commandcommand

which which cmdcmd LocationLocation

Page 30: Introduction to UNIX

UNIX Intro. 30

locate locate cmdcmd List files with List files with cmdcmd in in their name (or path)their name (or path)

locate gamelocate game

Output of these commands can be very Output of these commands can be very long. See a screenful at a time with: long. See a screenful at a time with: | more| more

locate game | morelocate game | more

apropos print | moreapropos print | more

Press spacebar to go on; Press spacebar to go on; ^C ^C to stop.to stop.

Page 31: Introduction to UNIX

UNIX Intro. 31

5.3. UNIX Books5.3. UNIX Books A Student’s Guide to UNIXA Student’s Guide to UNIX, Harley Hahn, , Harley Hahn,

McGraw-Hill, 1993.McGraw-Hill, 1993.

A Practical Guide to the UNIX SystemA Practical Guide to the UNIX System , , Mark G. Sobell, Benjamin-Cummings, Mark G. Sobell, Benjamin-Cummings, 3rd Edition, 1995.3rd Edition, 1995.

An Introduction to Berkeley UNIXAn Introduction to Berkeley UNIX, , Paul Wang, Wadsworth, 1992.Paul Wang, Wadsworth, 1992.

Page 32: Introduction to UNIX

UNIX Intro. 32

6. The UNIX File System6. The UNIX File System

6.1. 6.1. An upside-down TreeAn upside-down Tree

6.2. 6.2. Some System DirectoriesSome System Directories

6.3. 6.3. Where do you login?Where do you login?

6.4. 6.4. PathnamesPathnames

6.5.6.5. Commands and PathnamesCommands and Pathnames

Page 33: Introduction to UNIX

UNIX Intro. 33

6.1. An upside-down Tree6.1. An upside-down Tree A simplified UNIX directory/file system:A simplified UNIX directory/file system:

/

etc bin export

home

user

ad s3910120

dev tmp

exam.txt work hobby.c proj1

date cal. . .

. . . . .

. .

. . .

. . . . . .. . .

. . .

Page 34: Introduction to UNIX

UNIX Intro. 34

6.2. Some System Directories6.2. Some System Directories

// rootroot directory directory

/bin/bin commandscommands

/etc/etc system data filessystem data files(e.g. (e.g. /etc/passwd/etc/passwd))

/dev/dev files representing I/O devicesfiles representing I/O devices

Page 35: Introduction to UNIX

UNIX Intro. 35

6.3. Where do you login?6.3. Where do you login? Your Your home directoryhome directory, which is named after , which is named after

your login ID. your login ID. /

s3910120

hobby.c proj1

export

home

user

s3910120’shome dir.

. . .

Page 36: Introduction to UNIX

UNIX Intro. 36

6.4. Pathnames6.4. Pathnames

A A pathnamepathname is a sequence of directory is a sequence of directory names (separated by /’s) which identifies names (separated by /’s) which identifies the location of a directory.the location of a directory.

There are two sorts of pathnamesThere are two sorts of pathnames– absolute pathnamesabsolute pathnames– relative pathnamerelative pathname

Page 37: Introduction to UNIX

UNIX Intro. 37

Absolute PathnamesAbsolute Pathnames

The sequence of directory names between The sequence of directory names between the top of the tree (the the top of the tree (the rootroot) and the ) and the directory of interest. directory of interest.

For example:For example:/bin/bin

/etc/terminfo/etc/terminfo

/export/user/home/ad/export/user/home/ad

/export/user/home/s3910120/proj1/export/user/home/s3910120/proj1

Page 38: Introduction to UNIX

UNIX Intro. 38

Relative PathnamesRelative Pathnames The sequence of directory names The sequence of directory names belowbelow the the

directory where you are now to the directory directory where you are now to the directory of interest. of interest.

If you are interested in the directory If you are interested in the directory proj1proj1::proj1proj1 if you are in if you are in s3910120s3910120

s3910120/proj1s3910120/proj1 if you are in if you are in homehome

home/s3910120/proj1home/s3910120/proj1 if you are in if you are in useruser

Page 39: Introduction to UNIX

UNIX Intro. 39

7. Working with Directories7. Working with Directories

7.1. 7.1. Moving between DirectoriesMoving between Directories

7.2. 7.2. Special Directory NamesSpecial Directory Names

7.3. 7.3. Investigate the SystemInvestigate the System

7.4. 7.4. Making / Deleting / Renaming Making / Deleting / Renaming DirectoriesDirectories

Page 40: Introduction to UNIX

UNIX Intro. 40

7.1. Moving between Directories7.1. Moving between Directories

s3910120’s home directory:s3910120’s home directory:

s3910120

hobby.c proj1

. . .

proj2

. . .

Page 41: Introduction to UNIX

UNIX Intro. 41

If you are in directory If you are in directory s3910120s3910120 how do how do you move to directory you move to directory proj1proj1??cd proj1cd proj1

You are now in You are now in proj1proj1. This is called the . This is called the current working directorycurrent working directory..

Page 42: Introduction to UNIX

UNIX Intro. 42

pwdpwd Print name of current Print name of current working directoryworking directory

Move back to directory Move back to directory s3910120s3910120 (the (the parent directory):parent directory):cd ..cd ..

Page 43: Introduction to UNIX

UNIX Intro. 43

When in When in proj1proj1, move to , move to proj2proj2 with one with one command:command:cd ../proj2cd ../proj2

../proj2 ../proj2 is a is a relativerelative pathname pathname

Page 44: Introduction to UNIX

UNIX Intro. 44

7.2. Special Directory Names7.2. Special Directory Names

// The root directoryThe root directory .. The current working The current working

directorydirectory .... The parent directory The parent directory

(of your current directory)(of your current directory) ~~ Your home directoryYour home directory ~user~user Home directory of Home directory of useruser

Page 45: Introduction to UNIX

UNIX Intro. 45

ExamplesExamples

cd /cd / Change to root directoryChange to root directory cd ~cd ~ Change to home directoryChange to home directory cdcd (Special case; means (Special case; means cd ~cd ~)) cd ~adcd ~ad Change to my home dir.Change to my home dir. cd ../..cd ../.. Go up two levels.Go up two levels.

Page 46: Introduction to UNIX

UNIX Intro. 46

7.3. Investigate the System7.3. Investigate the System

Use Use cdcd cat filecat file List List filefile

cd /etccd /etc

cat passwdcat passwd

lsls Directory listingDirectory listinglsls List current dir.List current dir.

ls /etcls /etc List List /etc/etc

ls -Fls -F -F option shows types-F option shows types

Page 47: Introduction to UNIX

UNIX Intro. 47

7.4. Making / Deleting / 7.4. Making / Deleting / Renaming DirectoriesRenaming Directories

Usually, you can only create directories (or Usually, you can only create directories (or delete or rename them) in your home delete or rename them) in your home directory or directories below it.directory or directories below it.

mkdirmkdir Make a directoryMake a directory

rmdirrmdir Delete a directoryDelete a directory

mvmv Rename a directoryRename a directory

Page 48: Introduction to UNIX

UNIX Intro. 48

Create a Create a lablab directory in your home directory:directory in your home directory:cd ~cd ~

mkdir labmkdir lab

Create two directories inside the Create two directories inside the lablab directory:directory:cd labcd lab

mkdir week1mkdir week1

mkdir week2mkdir week2

Page 49: Introduction to UNIX

UNIX Intro. 49

Delete the Delete the week1week1 directory:directory:rmdir week1rmdir week1

Change the name of Change the name of week2week2 to to all-weeksall-weeksmv week2 all-weeksmv week2 all-weeks

Page 50: Introduction to UNIX

UNIX Intro. 50

8. Working with Files8. Working with Files

8.1. 8.1. Creating a Text FileCreating a Text File

8.2. 8.2. Listing FilesListing Files

8.3. 8.3. Filename ConventionsFilename Conventions

8.4. 8.4. Other Basic CommandsOther Basic Commands

8.5. 8.5. PrintingPrinting

8.6. 8.6. I/O RedirectionI/O Redirection

Page 51: Introduction to UNIX

UNIX Intro. 51

8.1. Creating a Text File8.1. Creating a Text File

A quick way:A quick way:cat > filecat > file

This will feed the text you type at the keyboard This will feed the text you type at the keyboard into into filefile until you type until you type ^D ^D ((CONTROL CONTROL and a D and a D together).together).

A more powerful way is to use A more powerful way is to use vivi, a full screen , a full screen editor (see later).editor (see later).

Page 52: Introduction to UNIX

UNIX Intro. 52

8.2. Listing Files8.2. Listing Files

cat file cat file List the fileList the filecat hobby.ccat hobby.c

cat /etc/passwdcat /etc/passwd

cat /usr/dict/wordscat /usr/dict/words ((^C ^C to stop)to stop)

more filemore file List the file a screen at List the file a screen at a time. Type spacebar a time. Type spacebar to go on; to go on; ^C ^C to stopto stop

Page 53: Introduction to UNIX

UNIX Intro. 53

less fileless file Like Like moremore but more but more powerfulpowerful

head filehead file List the List the firstfirst few lines few lines

tail filetail file List the List the lastlast few lines few lines

Page 54: Introduction to UNIX

UNIX Intro. 54

8.3. Filename Conventions8.3. Filename Conventions

Many files have a name and an extension:Many files have a name and an extension:file.cfile.c A C programA C program

file.cppfile.cpp A C++ programA C++ program

file.txtfile.txt A text fileA text file

However, you can call a file However, you can call a file anythinganything. It . It doesn’t have to have an extension.doesn’t have to have an extension.

Page 55: Introduction to UNIX

UNIX Intro. 55

8.4. Other Basic Commands8.4. Other Basic Commands

cp file1 file2cp file1 file2 Copy Copy file1file1, , making making file2file2

mv file1 file2mv file1 file2 Rename Rename file1file1 as as file2file2

rm filerm file Delete Delete filefile

rm -i filerm -i file Double-check firstDouble-check first

Page 56: Introduction to UNIX

UNIX Intro. 56

wc filewc file Counts the lines, Counts the lines, words, words,

characters characters in in filefile

grep string filegrep string file Search Search filefile for for stringstring

Page 57: Introduction to UNIX

UNIX Intro. 57

List lines containing ‘Andrew’ in List lines containing ‘Andrew’ in /etc/passwd/etc/passwd

grep Andrew /etc/passwdgrep Andrew /etc/passwd

Lines containing ‘printf(‘ in Lines containing ‘printf(‘ in hobby.chobby.c

grep grep ‘‘printf(printf(‘‘ hobby.c hobby.c

Lines Lines startingstarting with ‘loca’ in with ‘loca’ in /usr/dict/words/usr/dict/words

grep grep ^̂loca /usr/dict/wordsloca /usr/dict/words

Page 58: Introduction to UNIX

UNIX Intro. 58

8.5. Printing8.5. Printing

lpr filelpr file Print Print filefile

lpqlpq List the print queue. List the print queue. Each print job has a Each print job has a number.number.

lprm job-numberlprm job-number Remove that Remove that print jobprint job

Page 59: Introduction to UNIX

UNIX Intro. 59

You may have to name the printer with You may have to name the printer with the the -P -P option:option:lpr -Plj5 hobby.clpr -Plj5 hobby.c

lpqlpq and and lprmlprm understand the understand the -P -P optionoption

Page 60: Introduction to UNIX

UNIX Intro. 60

8.6. I/O Redirection8.6. I/O Redirection

Most commands output to the screenMost commands output to the screenlsls

Output can be Output can be redirectedredirected to a file with to a file with‘>‘‘>‘::ls > dir.txtls > dir.txt

cal 1997 > year1997cal 1997 > year1997

Output can be Output can be appendedappended to a file with to a file with ‘>>‘‘>>‘cal 1997 > yearscal 1997 > years

cal 1998 >> yearscal 1998 >> years

Page 61: Introduction to UNIX

UNIX Intro. 61

Concatenate two files:Concatenate two files:cat f1 f2 > fscat f1 f2 > fs

Input redirection (less common) uses ‘<‘Input redirection (less common) uses ‘<‘wc < yearswc < years

Combine input and output redirection:Combine input and output redirection:wc < years > year-countswc < years > year-counts

Page 62: Introduction to UNIX

UNIX Intro. 62

10. 10. vivi vivi is the standard UNIX text editoris the standard UNIX text editor

ContentsContents

1.1. Why use Why use vivi??

2.2. vivi BasicsBasics

3.3. Moving AroundMoving Around

4.4. Inserting TextInserting Text

Page 63: Introduction to UNIX

UNIX Intro. 63

5.5. DeletionDeletion

6.6. Cut & PasteCut & Paste

7.7. File-related CommandsFile-related Commands

8.8. Text SubstitutionText Substitution

Page 64: Introduction to UNIX

UNIX Intro. 64

1. Why use vi?1. Why use vi?

very powerfulvery powerful useful simple subset of commandsuseful simple subset of commands portable (PCs, mainframes, etc.)portable (PCs, mainframes, etc.) designed for slow networksdesigned for slow networks full-screenfull-screen

Page 65: Introduction to UNIX

UNIX Intro. 65

2. vi Basics2. vi Basics

2.1.2.1. Starting viStarting vi

2.2.2.2. Two ModesTwo Modes

2.3.2.3. The vi WindowThe vi Window

2.4.2.4. When to type When to type RETURNRETURN

2.5.2.5. Finishing a vi SessionFinishing a vi Session

Page 66: Introduction to UNIX

UNIX Intro. 66

2.1. Starting vi2.1. Starting vi

vi filevi file Start editing Start editing filefile

Changes are stored in a buffer, so you must Changes are stored in a buffer, so you must save to change the file. save to change the file.

If the machine crashes, the buffer can If the machine crashes, the buffer can usually be recovered (see later).usually be recovered (see later).

Page 67: Introduction to UNIX

UNIX Intro. 67

2.2. Two Modes2.2. Two Modes Command modeCommand mode

– move cursor, save, delete text, quit vi, etc.move cursor, save, delete text, quit vi, etc.

Input modeInput mode– for inserting textfor inserting text– start by typing i; finish with start by typing i; finish with ESCESC

– cannot quit, delete, etc. in this modecannot quit, delete, etc. in this mode

– If in doubt, press If in doubt, press ESCESC a few timesa few times. This will put you . This will put you back in command mode.back in command mode.

Page 68: Introduction to UNIX

UNIX Intro. 68

2.3. The vi Window2.3. The vi Window

Bottom line is the Bottom line is the statusstatus line line

Some, Some, butbut not allnot all, commands are shown on , commands are shown on the status line.the status line.

Often you type a command and nothing Often you type a command and nothing appears on the screen!appears on the screen!

Page 69: Introduction to UNIX

UNIX Intro. 69

ColonColon commands (e.g. commands (e.g. :q!:q!) and ) and searchsearch commands (e.g. commands (e.g. /text/text) require a ) require a RETURNRETURN..

Commands that start with a Commands that start with a letterletter (e.g. (e.g. ZZZZ, , GG) and control characters (e.g. ) and control characters (e.g. ^L^L) ) do do notnot require a require a RETURNRETURN

2.4. When to type 2.4. When to type RETURNRETURN

Page 70: Introduction to UNIX

UNIX Intro. 70

2.5. Finishing a vi Session2.5. Finishing a vi Session

Get to command mode (press Get to command mode (press ESCESCs)s)

ZZZZ save changes to the file and quitsave changes to the file and quit(no (no RETURNRETURN))

:q!:q! quit without savingquit without saving(press (press RETURNRETURN))

Page 71: Introduction to UNIX

UNIX Intro. 71

3. Moving Around3. Moving Around

3.1.3.1. Basic Cursor MovementsBasic Cursor Movements

3.2.3.2. Larger MovesLarger Moves

Page 72: Introduction to UNIX

UNIX Intro. 72

3.1. Basic Cursor Movements3.1. Basic Cursor Movements

hh move cursor one place to leftmove cursor one place to left

jj down onedown one

kk up oneup one

ll right oneright one

ww move forward one wordmove forward one word

bb back one wordback one word

No RETURNrequired!

Page 73: Introduction to UNIX

UNIX Intro. 73

3.2. Larger Moves3.2. Larger Moves

GG go to last linego to last line<number>G<number>G go to line go to line numbernumber

10G10G

^G^G shows the current line numbershows the current line number

^F^F Forward a screenForward a screen^B^B Back a screenBack a screen

Page 74: Introduction to UNIX

UNIX Intro. 74

/text/text Search forward for Search forward for texttext

/func/func search for search for funcfunc

/printf(/printf( search for search for printf(printf(

//^̂foofoo search for search for foofoo at start of line at start of line

Type RETURN!

Page 75: Introduction to UNIX

UNIX Intro. 75

4. Inserting Text4. Inserting Text

Move to insertion pointMove to insertion point

Switch to input mode:Switch to input mode: i i

Start typing; Start typing; BACKSPACE BACKSPACE or or DELETE DELETE

for deletionfor deletion

ESCESC finish; back in command modefinish; back in command mode

No RETURN

Page 76: Introduction to UNIX

UNIX Intro. 76

Over a slow network, the screen may not Over a slow network, the screen may not refresh properlyrefresh properly

^L^L refresh screen (in command mode)refresh screen (in command mode)

Page 77: Introduction to UNIX

UNIX Intro. 77

5. Deletion5. Deletion

Must be in command mode.Must be in command mode.

xx Delete Delete charactercharacter that cursor is on. that cursor is on.

dddd Delete current Delete current lineline..

DD Delete from cursor position Delete from cursor position to to end of lineend of line

uu UndoUndo last command last command

Page 78: Introduction to UNIX

UNIX Intro. 78

:i,jd:i,jd Delete lines i to jDelete lines i to j:23,29d:23,29d Delete lines 23 to 29Delete lines 23 to 29

Special line numbers:Special line numbers:.. means the current line numbermeans the current line number

^̂ means line number 1means line number 1

$$ means last linemeans last line

:.,$d:.,$d Delete from current line Delete from current line to the end of file.to the end of file.

Page 79: Introduction to UNIX

UNIX Intro. 79

6. Cut & Paste6. Cut & Paste

6.1.6.1. Cut & Paste MeaningCut & Paste Meaning

6.2.6.2. Cut & Paste with Deleted TextCut & Paste with Deleted Text

6.3.6.3. Moving TextMoving Text

Page 80: Introduction to UNIX

UNIX Intro. 80

6.1. Cut & Paste Meaning6.1. Cut & Paste Meaning

CutCut commands remove text from the commands remove text from the screen, and store it in a bufferscreen, and store it in a buffer

PastePaste commands copy text from the commands copy text from the buffer to the screenbuffer to the screen

Page 81: Introduction to UNIX

UNIX Intro. 81

6.2. Cut & Paste with Deleted 6.2. Cut & Paste with Deleted TextText

d or dd or D d or dd or D delete from screen and delete from screen and store text in a bufferstore text in a buffer

move cursor to new locationmove cursor to new location

pp paste contents of buffer paste contents of buffer to right of cursor posnto right of cursor posn

Page 82: Introduction to UNIX

UNIX Intro. 82

6.3. Moving Text6.3. Moving Text Cut and Paste with moveCut and Paste with move

:i,j:i,jmmkk move lines i through j to move lines i through j to start after line kstart after line k

:3,8m10:3,8m10 move lines 3 to 8 to start after line 10move lines 3 to 8 to start after line 10

:20m.:20m. move line 20 to after the current linemove line 20 to after the current line

:1,.m$:1,.m$ move lines 1 through current line move lines 1 through current line to the bottomto the bottom

Page 83: Introduction to UNIX

UNIX Intro. 83

7. File-related Commands7. File-related Commands

:w file:w file writes writes vivi contents to contents to newnew file file:w >> file:w >> file appends to fileappends to file

:w! file:w! file writes over filewrites over file:w!:w! writes over input filewrites over input file

:r file:r file read in file; places it starting read in file; places it starting at current cursor positionat current cursor position

Page 84: Introduction to UNIX

UNIX Intro. 84

Page 85: Introduction to UNIX

UNIX Intro. 85

The C LanguageThe C Language

Page 86: Introduction to UNIX

UNIX Intro. 86

The C LanguageThe C Language

Currently, the most commonly-used Currently, the most commonly-used language for embedded systemslanguage for embedded systems

““High-level assembly”High-level assembly” Very portable: compilers exist for virtually Very portable: compilers exist for virtually

every processorevery processor Easy-to-understand compilation Easy-to-understand compilation Produces efficient codeProduces efficient code Fairly conciseFairly concise

Page 87: Introduction to UNIX

UNIX Intro. 87

C HistoryC History

Developed between 1969 and 1973 along with Developed between 1969 and 1973 along with UnixUnix

Due mostly to Dennis RitchieDue mostly to Dennis Ritchie Designed for systems programmingDesigned for systems programming

– Operating systemsOperating systems– Utility programsUtility programs– CompilersCompilers– FiltersFilters

Evolved from B, which evolved from BCPLEvolved from B, which evolved from BCPL

Page 88: Introduction to UNIX

UNIX Intro. 88

C HistoryC History

Original machine (DEC PDP-Original machine (DEC PDP-11) was very small11) was very small– 24K bytes of memory, 12K used 24K bytes of memory, 12K used

for operating systemfor operating system

Written when computers were Written when computers were big, capital equipmentbig, capital equipment– Group would get one, develop Group would get one, develop

new language, OSnew language, OS

Page 89: Introduction to UNIX

UNIX Intro. 89

C HistoryC History

Many language features designed to reduce Many language features designed to reduce memorymemory– Forward declarations required for everythingForward declarations required for everything– Designed to work in one pass: must know everythingDesigned to work in one pass: must know everything– No function nestingNo function nesting

PDP-11 was byte-addressedPDP-11 was byte-addressed– Now standardNow standard– Meant BCPL’s word-based model was insufficientMeant BCPL’s word-based model was insufficient

Page 90: Introduction to UNIX

UNIX Intro. 90

Hello World in CHello World in C

#include <stdio.h>#include <stdio.h>

void main()void main(){{ printf(“Hello, world!\n”);printf(“Hello, world!\n”);}}

Preprocessor used to share information among source files

- Clumsy

+ Cheaply implemented

+ Very flexible

Page 91: Introduction to UNIX

UNIX Intro. 91

Hello World in CHello World in C

#include <stdio.h>#include <stdio.h>

void main()void main(){{ printf(“Hello, world!\n”);printf(“Hello, world!\n”);}}

Program mostly a collection of functions

“main” function special: the entry point

“void” qualifier indicates function does not return anything

I/O performed by a library function: not included in the language

Page 92: Introduction to UNIX

UNIX Intro. 92

Euclid’s algorithm in CEuclid’s algorithm in C

int gcd(int m, int n)int gcd(int m, int n){{ int r;int r; while ( (r = m % n) != 0) {while ( (r = m % n) != 0) { m = n;m = n; n = r;n = r; }} return n;return n;}}

“New Style” function declaration lists number and type of arguments

Originally only listed return type. Generated code did not care how many arguments were actually passed.

Arguments are call-by-value

Page 93: Introduction to UNIX

UNIX Intro. 93

Euclid’s algorithm in CEuclid’s algorithm in C

int gcd(int m, int n)int gcd(int m, int n){{ int r;int r; while ( (r = m % n) != 0) {while ( (r = m % n) != 0) { m = n;m = n; n = r;n = r; }} return n;return n;}}

Automatic variable

Storage allocated on stack when function entered, released when it returns.

All parameters, automatic variables accessed w.r.t. frame pointer.

Extra storage needed while evaluating large expressions also placed on the stack

nm

ret. addr.r

Frame pointer Stack

pointer

Excess arguments simply ignored

Page 94: Introduction to UNIX

UNIX Intro. 94

Euclid’s algorithm in CEuclid’s algorithm in C

int gcd(int m, int n)int gcd(int m, int n){{ int r;int r; while ( (r = m % n) != 0) {while ( (r = m % n) != 0) { m = n;m = n; n = r;n = r; }} return n;return n;}}

Expression: C’s basic type of statement.

Arithmetic and logical

Assignment (=) returns a value, so can be used in expressions

% is remainder

!= is not equal

Page 95: Introduction to UNIX

UNIX Intro. 95

Euclid’s algorithm in CEuclid’s algorithm in C

int gcd(int m, int n)int gcd(int m, int n){{ int r;int r; while ( (r = m % n) != 0) {while ( (r = m % n) != 0) { m = n;m = n; n = r;n = r; }} return n;return n;}}

High-level control-flow statement. Ultimately becomes a conditional branch.

Supports “structured programming”

Each function returns a single value, usually an integer. Returned through a specific register by convention.

Page 96: Introduction to UNIX

UNIX Intro. 96

Euclid Compiled on PDP-11Euclid Compiled on PDP-11

.globl _gcd.globl _gcd r0-r7r0-r7

.text.text PC is r7, SP is r6, FP is r5PC is r7, SP is r6, FP is r5_gcd:_gcd: jsr r5,rsavejsr r5,rsave save sp in frame pointer r5save sp in frame pointer r5L2:mov 4(r5),r1L2:mov 4(r5),r1 r1 = nr1 = n sxt r0sxt r0 sign extendsign extend div 6(r5),r0div 6(r5),r0 m / n = r0,r1m / n = r0,r1 mov r1,-10(r5)mov r1,-10(r5) r = m % nr = m % n jeq L3jeq L3 mov 6(r5),4(r5)mov 6(r5),4(r5)m = nm = n mov -10(r5),6(r5)mov -10(r5),6(r5) n = rn = r jbr L2jbr L2L3:mov 6(r5),r0L3:mov 6(r5),r0 return n in r0return n in r0 jbr L1jbr L1L1:jmp rretrnL1:jmp rretrn restore sp ptr, returnrestore sp ptr, return

int gcd(int m, int n)int gcd(int m, int n){{ int r;int r; while ( (r = m % n) != 0) {while ( (r = m % n) != 0) { m = n;m = n; n = r;n = r; }} return n;return n;}}

Page 97: Introduction to UNIX

UNIX Intro. 97

Euclid Compiled on PDP-11Euclid Compiled on PDP-11

.globl _gcd.globl _gcd

.text.text_gcd:_gcd: jsr r5,rsavejsr r5,rsaveL2:mov 4(r5),r1L2:mov 4(r5),r1 sxt r0sxt r0 div 6(r5),r0div 6(r5),r0 mov r1,-10(r5)mov r1,-10(r5) jeq L3jeq L3 mov 6(r5),4(r5)mov 6(r5),4(r5) mov -10(r5),6(r5)mov -10(r5),6(r5) jbr L2jbr L2L3:mov 6(r5),r0L3:mov 6(r5),r0 jbr L1jbr L1L1:jmp rretrnL1:jmp rretrn

Very natural mapping from C into PDP-11 instructions.

Complex addressing modes make frame-pointer-relative accesses easy.

Another idiosyncrasy: registers were memory-mapped, so taking address of a variable in a register is straightforward.

Page 98: Introduction to UNIX

UNIX Intro. 98

Pieces of CPieces of C

Types and VariablesTypes and Variables– Definitions of data in memoryDefinitions of data in memory

ExpressionsExpressions– Arithmetic, logical, and assignment operators in an Arithmetic, logical, and assignment operators in an

infix notationinfix notation StatementsStatements

– Sequences of conditional, iteration, and branching Sequences of conditional, iteration, and branching instructionsinstructions

FunctionsFunctions– Groups of statements and variables invoked recursivelyGroups of statements and variables invoked recursively

Page 99: Introduction to UNIX

UNIX Intro. 99

C TypesC Types

Basic types: char, int, float, and doubleBasic types: char, int, float, and double Meant to match the processor’s native typesMeant to match the processor’s native types

– Natural translation into assemblyNatural translation into assembly– Fundamentally nonportableFundamentally nonportable

Declaration syntax: string of specifiers followed by Declaration syntax: string of specifiers followed by a declaratora declarator

Declarator’s notation matches that in an expressionDeclarator’s notation matches that in an expression Access a symbol using its declarator and get the Access a symbol using its declarator and get the

basic type backbasic type back

Page 100: Introduction to UNIX

UNIX Intro. 100

C Type ExamplesC Type Examples

int i;int i;int *j, k;int *j, k;unsigned char *ch;unsigned char *ch;float f[10];float f[10];char nextChar(int, char nextChar(int, char*);char*);

int a[3][5][10];int a[3][5][10];int *func1(float);int *func1(float);int (*func2)(void);int (*func2)(void);

Integer

j: pointer to integer, int k

ch: pointer to unsigned char

Array of 10 floats

2-arg function

Array of three arrays of five …

function returning int *

pointer to function returning int

Page 101: Introduction to UNIX

UNIX Intro. 101

C TypedefC Typedef

Type declarations recursive, complicated.Type declarations recursive, complicated. Name new types with typedef Name new types with typedef

Instead ofInstead of

int (*func2)(void)int (*func2)(void)

useuse

typedef int func2t(void);typedef int func2t(void);

func2t *func2;func2t *func2;

Page 102: Introduction to UNIX

UNIX Intro. 102

C StructuresC Structures

A struct is an object with named fields:A struct is an object with named fields:

struct {struct { char *name;char *name; int x, y;int x, y; int h, w;int h, w;} box;} box;

Accessed using “dot” notation:Accessed using “dot” notation:

box.x = 5;box.x = 5;box.y = 2;box.y = 2;

Page 103: Introduction to UNIX

UNIX Intro. 103

Struct bit-fieldsStruct bit-fields

Way to aggressively pack data in memoryWay to aggressively pack data in memory

struct {struct { unsigned int baud : 5;unsigned int baud : 5; unsigned int div2 : 1;unsigned int div2 : 1; unsigned int use_external_clock : 1;unsigned int use_external_clock : 1;} flags;} flags; Compiler will pack these fields into wordsCompiler will pack these fields into words Very implementation dependent: no guarantees of ordering, Very implementation dependent: no guarantees of ordering,

packing, etc.packing, etc. Usually less efficientUsually less efficient

– Reading a field requires masking and shiftingReading a field requires masking and shifting

Page 104: Introduction to UNIX

UNIX Intro. 104

C UnionsC Unions

Can store objects of different types at different timesCan store objects of different types at different times

union {union { int ival;int ival; float fval;float fval; char *sval;char *sval;};};

Useful for arrays of dissimilar objectsUseful for arrays of dissimilar objects Potentially very dangerousPotentially very dangerous Good example of C’s philosophyGood example of C’s philosophy

– Provide powerful mechanisms that can be abusedProvide powerful mechanisms that can be abused

Page 105: Introduction to UNIX

UNIX Intro. 105

Alignment of data in structsAlignment of data in structs

Most processors require n-byte objects to be Most processors require n-byte objects to be in memory at address n*kin memory at address n*k

Side effect of wide memory bussesSide effect of wide memory busses E.g., a 32-bit memory busE.g., a 32-bit memory bus Read from address 3 requires two accesses, Read from address 3 requires two accesses,

shiftingshifting4 3 2

1

4 3 2 1

Page 106: Introduction to UNIX

UNIX Intro. 106

Alignment of data in structsAlignment of data in structs

Compilers add “padding” to structs to ensure proper alignment, Compilers add “padding” to structs to ensure proper alignment, especially for arraysespecially for arrays

Pad to ensure alignment of largest object (with biggest Pad to ensure alignment of largest object (with biggest requirement)requirement)

struct {struct { char a;char a; int b;int b; char c;char c;}}

Moral: rearrange to save memoryMoral: rearrange to save memory

abbbbc

abbbbc

Pad

Page 107: Introduction to UNIX

UNIX Intro. 107

C Storage ClassesC Storage Classes

#include <stdlib.h>#include <stdlib.h>

int global_static;int global_static;static int file_static;static int file_static;

void foo(int auto_param)void foo(int auto_param){{ static int func_static;static int func_static; int auto_i, auto_a[10];int auto_i, auto_a[10]; double *auto_d = double *auto_d = malloc(sizeof(double)*5);malloc(sizeof(double)*5);

}}

Linker-visible. Allocated at fixed location

Visible within file. Allocated at fixed location.

Visible within func. Allocated at fixed location.

Page 108: Introduction to UNIX

UNIX Intro. 108

C Storage ClassesC Storage Classes

#include <stdlib.h>#include <stdlib.h>

int global_static;int global_static;static int file_static;static int file_static;

void foo(int auto_param)void foo(int auto_param){{ static int func_static;static int func_static; int auto_i, auto_a[10];int auto_i, auto_a[10]; double *auto_d = double *auto_d = malloc(sizeof(double)*5);malloc(sizeof(double)*5);

}}

Space allocated on stack by function.

Space allocated on stack by caller.

Space allocated on heap by library routine.

Page 109: Introduction to UNIX

UNIX Intro. 109

malloc() and free()malloc() and free()

Library routines for managing the heapLibrary routines for managing the heap

int *a;int *a;a = (int *) malloc(sizeof(int) * k); a = (int *) malloc(sizeof(int) * k); a[5] = 3;a[5] = 3;free(a);free(a);

Allocate and free arbitrary-sized chunks of Allocate and free arbitrary-sized chunks of memory in any ordermemory in any order

Page 110: Introduction to UNIX

UNIX Intro. 110

malloc() and free()malloc() and free()

More flexible than automatic variables (stacked)More flexible than automatic variables (stacked) More costly in time and spaceMore costly in time and space

– malloc() and free() use complicated non-constant-time malloc() and free() use complicated non-constant-time algorithmsalgorithms

– Each block generally consumes two additional words of memoryEach block generally consumes two additional words of memory Pointer to next empty blockPointer to next empty block Size of this blockSize of this block

Common source of errorsCommon source of errors– Using uninitialized memoryUsing uninitialized memory– Using freed memoryUsing freed memory– Not allocating enoughNot allocating enough– Neglecting to free disused blocks (memory leaks)Neglecting to free disused blocks (memory leaks)

Page 111: Introduction to UNIX

UNIX Intro. 111

malloc() and free()malloc() and free()

Memory usage errors so pervasive, entire Memory usage errors so pervasive, entire successful company (Pure Software) founded to successful company (Pure Software) founded to sell tool to track them downsell tool to track them down

Purify tool inserts code that verifies each memory Purify tool inserts code that verifies each memory accessaccess

Reports accesses of uninitialized memory, Reports accesses of uninitialized memory, unallocated memory, etc.unallocated memory, etc.

Publicly-available Electric Fence tool does Publicly-available Electric Fence tool does something similarsomething similar

Page 112: Introduction to UNIX

UNIX Intro. 112

Dynamic Storage AllocationDynamic Storage Allocation

What are malloc() and free() actually What are malloc() and free() actually doing?doing?

Pool of memory segments:Pool of memory segments:Free

malloc( )

Page 113: Introduction to UNIX

UNIX Intro. 113

Dynamic Storage AllocationDynamic Storage Allocation

Rules:Rules:– Each segment contiguous in memory (no holes)Each segment contiguous in memory (no holes)– Segments do not move once allocatedSegments do not move once allocated

malloc()malloc()– Find memory area large enough for segmentFind memory area large enough for segment– Mark that memory is allocatedMark that memory is allocated

free()free()– Mark the segment as unallocatedMark the segment as unallocated

Page 114: Introduction to UNIX

UNIX Intro. 114

Dynamic Storage AllocationDynamic Storage Allocation

Three issues:Three issues:

How to maintain information about free memoryHow to maintain information about free memory

The algorithm for locating a suitable blockThe algorithm for locating a suitable block

The algorithm for freeing an allocated blockThe algorithm for freeing an allocated block

Page 115: Introduction to UNIX

UNIX Intro. 115

Simple Dynamic Storage Simple Dynamic Storage AllocationAllocation Three issues:Three issues:

How to maintain information about free memoryHow to maintain information about free memory– Linked listLinked list

The algorithm for locating a suitable blockThe algorithm for locating a suitable block– First-fitFirst-fit

The algorithm for freeing an allocated blockThe algorithm for freeing an allocated block– Coalesce adjacent free blocksCoalesce adjacent free blocks

Page 116: Introduction to UNIX

UNIX Intro. 116

Simple Dynamic Storage Simple Dynamic Storage AllocationAllocation

Next

Size

Next

SizeSizeFree block Allocated block

malloc( )

First large-enough free block selected

Free block divided into two

Previous next pointer updated

Newly-allocated region begins with a size value

Page 117: Introduction to UNIX

UNIX Intro. 117

Simple Dynamic Storage Simple Dynamic Storage AllocationAllocation

free(a)

Appropriate position in free list identified

Newly-freed region added to adjacent free regions

Page 118: Introduction to UNIX

UNIX Intro. 118

Dynamic Storage AllocationDynamic Storage Allocation

Many, many variantsMany, many variants Other “fit” algorithmsOther “fit” algorithms Segregation of objects by sizesSegregation of objects by sizes

– 8-byte objects in one region, 16 in another, etc.8-byte objects in one region, 16 in another, etc. More intelligent list structuresMore intelligent list structures

Page 119: Introduction to UNIX

UNIX Intro. 119

Memory PoolsMemory Pools

An alternative: Memory poolsAn alternative: Memory pools Separate management policy for each poolSeparate management policy for each pool

Stack-based pool: can only free whole pool at onceStack-based pool: can only free whole pool at once– Very cheap operationVery cheap operation– Good for build-once data structures (e.g., compilers)Good for build-once data structures (e.g., compilers)

Pool for objects of a single sizePool for objects of a single size– Useful in object-oriented programsUseful in object-oriented programs

Not part of the C standard libraryNot part of the C standard library

Page 120: Introduction to UNIX

UNIX Intro. 120

ArraysArrays Array: sequence of identical Array: sequence of identical objects in memoryobjects in memory

int a[10];int a[10]; means space for means space for ten integersten integers

Filippo Brunelleschi, Ospdale degli Innocenti, Firenze, Italy, 1421

By itself, a is the address of the first integer

*a and a[0] mean the same thing

The address of a is not stored in memory: the compiler inserts code to compute it when it appears

Ritchie calls this interpretation the biggest conceptual jump from BCPL to C

Page 121: Introduction to UNIX

UNIX Intro. 121

Multidimensional ArraysMultidimensional Arrays

Array declarations read right-to-leftArray declarations read right-to-left int a[10][3][2];int a[10][3][2]; ““an array of ten arrays of three arrays of an array of ten arrays of three arrays of

two ints”two ints” In memoryIn memory2 2 2

3

2 2 2

3

2 2 2

3

...

10

Seagram Building, Ludwig Mies van der Rohe,1957

Page 122: Introduction to UNIX

UNIX Intro. 122

Multidimensional ArraysMultidimensional Arrays

Passing a multidimensional array as an argument Passing a multidimensional array as an argument requires all but the first dimensionrequires all but the first dimension

int a[10][3][2];int a[10][3][2];void examine( a[][3][2] ) { … }void examine( a[][3][2] ) { … }

Address for an access such as Address for an access such as a[i][j][k]a[i][j][k] is is

a + k + 2*(j + 3*i)a + k + 2*(j + 3*i)

Page 123: Introduction to UNIX

UNIX Intro. 123

Multidimensional ArraysMultidimensional Arrays

Use arrays of pointers for variable-sized Use arrays of pointers for variable-sized multidimensional arraysmultidimensional arrays

You need to allocate space for and initialize You need to allocate space for and initialize the arrays of pointersthe arrays of pointers

int ***a;int ***a; a[3][5][4]a[3][5][4] expands to expands to *(*(*(a+3)+5)+4)*(*(*(a+3)+5)+4)

The value

int ** int * int

int ***a

Page 124: Introduction to UNIX

UNIX Intro. 124

C ExpressionsC Expressions

Traditional mathematical expressionsTraditional mathematical expressions

y = a*x*x + b*x + c;y = a*x*x + b*x + c;

Very rich set of expressionsVery rich set of expressions Able to deal with arithmetic and bit Able to deal with arithmetic and bit

manipulationmanipulation

Page 125: Introduction to UNIX

UNIX Intro. 125

C Expression ClassesC Expression Classes

arithmetic: arithmetic: + – * / % + – * / % comparison: comparison: == != < <= > >=== != < <= > >= bitwise logical: bitwise logical: & | ^ ~& | ^ ~ shifting: shifting: << >><< >> lazy logical: lazy logical: && || !&& || ! conditional: conditional: ? :? : assignment: assignment: = += -== += -= increment/decrement: increment/decrement: ++ --++ -- sequencing: sequencing: ,, pointer: pointer: * -> & []* -> & []

Page 126: Introduction to UNIX

UNIX Intro. 126

Bitwise operatorsBitwise operators

and: & or: | xor: ^ not: ~ left shift: << right shift: >>and: & or: | xor: ^ not: ~ left shift: << right shift: >> Useful for bit-field manipulationsUseful for bit-field manipulations

#define MASK 0x040#define MASK 0x040if (a & MASK) { … }if (a & MASK) { … } /* Check bits /* Check bits

*/*/c |= MASK;c |= MASK; /* Set bits *//* Set bits */c &= ~MASK;c &= ~MASK; /* Clear bits *//* Clear bits */d = (a & MASK) >> 4;d = (a & MASK) >> 4; /* Select field *//* Select field */

Page 127: Introduction to UNIX

UNIX Intro. 127

Lazy Logical OperatorsLazy Logical Operators

““Short circuit” tests save timeShort circuit” tests save time

if ( a == 3 && b == 4 && c == 5 ) { … }if ( a == 3 && b == 4 && c == 5 ) { … }equivalent toequivalent toif (a == 3) { if (b ==4) { if (c == 5) { … } } }if (a == 3) { if (b ==4) { if (c == 5) { … } } }

Evaluation order (left before right) provides safetyEvaluation order (left before right) provides safety

if ( i <= SIZE && a[i] == 0 ) { … }if ( i <= SIZE && a[i] == 0 ) { … }

                                                                                                      

               

Page 128: Introduction to UNIX

UNIX Intro. 128

Conditional OperatorConditional Operator

c = a < b ? a + 1 : b – 1;c = a < b ? a + 1 : b – 1;

Evaluate first expression. If true, evaluate second, otherwise Evaluate first expression. If true, evaluate second, otherwise evaluate third.evaluate third.

Puts almost statement-like behavior in expressions.Puts almost statement-like behavior in expressions.

BCPL allowed code in an expression:BCPL allowed code in an expression:

a := 5 + valof{ int i, s = 0; for (i = 0 ; i < 10 ; i++) s += a[I];a := 5 + valof{ int i, s = 0; for (i = 0 ; i < 10 ; i++) s += a[I]; return s; }return s; }

Page 129: Introduction to UNIX

UNIX Intro. 129

Side-effects in expressionsSide-effects in expressions

Evaluating an expression often has side-Evaluating an expression often has side-effectseffects

a++a++ increment a afterwardsincrement a afterwards

a = 5a = 5 changes the value of achanges the value of a

a = foo() a = foo() function foo may have function foo may have side-effectsside-effects

Page 130: Introduction to UNIX

UNIX Intro. 130

Pointer ArithmeticPointer Arithmetic

From BCPL’s view of the worldFrom BCPL’s view of the world Pointer arithmetic is natural: everything’s an integerPointer arithmetic is natural: everything’s an integerint *p, *q;int *p, *q;*(p+5)*(p+5) equivalent to equivalent to p[5]p[5] If p and q point into same array, If p and q point into same array, p – qp – q is number is number

of elements between p and q.of elements between p and q. Accessing fields of a pointed-to structure has a Accessing fields of a pointed-to structure has a

shorthand:shorthand:p->fieldp->field means means (*p).field(*p).field

Page 131: Introduction to UNIX

UNIX Intro. 131

C StatementsC Statements

ExpressionExpression ConditionalConditional

– if (expr) { … } else {…}if (expr) { … } else {…}– switch (expr) { case c1: case c2: … }switch (expr) { case c1: case c2: … }

IterationIteration– while (expr) { … }while (expr) { … } zero or more iterationszero or more iterations– do … while (expr)do … while (expr) at least one iterationat least one iteration– for ( init ; valid ; next ) { … }for ( init ; valid ; next ) { … }

JumpJump– goto labelgoto label– continue;continue; go to start of loopgo to start of loop– break;break; exit loop or switchexit loop or switch– return expr;return expr; return from functionreturn from function

Page 132: Introduction to UNIX

UNIX Intro. 132

The Switch StatementThe Switch Statement

Performs multi-way branchesPerforms multi-way branches

switch (expr) {switch (expr) {case 1: …case 1: … break;break;case 5:case 5:case 6: …case 6: … break;break;default: …default: … break;break;}}

tmp = expr;if (tmp == 1) goto L1else if (tmp == 5) goto L5else if (tmp == 6) goto L6else goto Default;L1: … goto Break;L5:;L6: … goto Break;Default: … goto Break;Break:

Page 133: Introduction to UNIX

UNIX Intro. 133

Switch Generates Interesting Switch Generates Interesting CodeCode Sparse case labels tested sequentiallySparse case labels tested sequentially

if (e == 1) goto L1;if (e == 1) goto L1;else if (e == 10) goto L2;else if (e == 10) goto L2;else if (e == 100) goto L3;else if (e == 100) goto L3;

Dense cases use a jump tableDense cases use a jump table

table = { L1, L2, Default, L4, L5 };table = { L1, L2, Default, L4, L5 };if (e >= 1 and e <= 5) goto table[e];if (e >= 1 and e <= 5) goto table[e];

Clever compilers may combine theseClever compilers may combine these

Page 134: Introduction to UNIX

UNIX Intro. 134

setjmp/longjmpsetjmp/longjmp

A way to exit from deeply nested functionsA way to exit from deeply nested functions A hack now a formal part of the standard libraryA hack now a formal part of the standard library

#include <setjmp.h>#include <setjmp.h>jmp_buf jmpbuf;jmp_buf jmpbuf;

void top(void) {void top(void) { switch (setjmp(jmpbuf)) {switch (setjmp(jmpbuf)) { case 0: child(); break;case 0: child(); break; case 1: /* longjmp called */ break;case 1: /* longjmp called */ break;} }} }

void deeplynested() { longjmp(jmpbuf, 1); }void deeplynested() { longjmp(jmpbuf, 1); }

Space for a return address and registers (including stack pointer, frame pointer)

Stores context, returns 0

Returns to context, making it appear setjmp() returned 1

Page 135: Introduction to UNIX

UNIX Intro. 135

The Macro PreprocessorThe Macro Preprocessor

Relatively late and awkward addition to the languageRelatively late and awkward addition to the language

Symbolic constantsSymbolic constants#define PI 3.1415926535#define PI 3.1415926535

Macros with arguments for emulating inliningMacros with arguments for emulating inlining#define min(x,y) ((x) < (y) ? (x) : (y))#define min(x,y) ((x) < (y) ? (x) : (y))

Conditional compilationConditional compilation#ifdef __STDC__#ifdef __STDC__

File inclusion for sharing of declarationsFile inclusion for sharing of declarations#include “myheaders.h”#include “myheaders.h”

Page 136: Introduction to UNIX

UNIX Intro. 136

Macro Preprocessor PitfallsMacro Preprocessor Pitfalls

Header file dependencies usually form a directed Header file dependencies usually form a directed acyclic graph (DAG)acyclic graph (DAG)

How do you avoid defining things twice?How do you avoid defining things twice?

Convention: surround each header (.h) file with a Convention: surround each header (.h) file with a conditional:conditional:

#ifndef __MYHEADER_H__#ifndef __MYHEADER_H__#define __MYHEADER_H__#define __MYHEADER_H__/* Declarations *//* Declarations */#endif#endif

Page 137: Introduction to UNIX

UNIX Intro. 137

Macro Preprocessor PitfallsMacro Preprocessor Pitfalls

Macros with arguments do not have function call Macros with arguments do not have function call semanticssemantics

Function Call:Function Call:– Each argument evaluated once, in undefined order, Each argument evaluated once, in undefined order,

before function is calledbefore function is called

Macro:Macro:– Each argument evaluated once every time it appears in Each argument evaluated once every time it appears in

expansion textexpansion text

Page 138: Introduction to UNIX

UNIX Intro. 138

Macro Preprocessor pitfallsMacro Preprocessor pitfalls

Example: the “min” functionExample: the “min” functionint min(int a, int b)int min(int a, int b) { if (a < b) return a; else return b; }{ if (a < b) return a; else return b; }#define min(a,b) ((a) < (b) ? (a) : (b))#define min(a,b) ((a) < (b) ? (a) : (b))

Identical for min(5,x)Identical for min(5,x) Different when evaluating expression has side-effect:Different when evaluating expression has side-effect:

min(a++,b)min(a++,b)– min function increments a oncemin function increments a once– min macro may increment a twice if a < bmin macro may increment a twice if a < b

Page 139: Introduction to UNIX

UNIX Intro. 139

Macro Preprocessor PitfallsMacro Preprocessor Pitfalls

Text substitution can expose unexpected groupingsText substitution can expose unexpected groupings

#define mult(a,b) a*b#define mult(a,b) a*bmult(5+3,2+4)mult(5+3,2+4) Expands to Expands to 5 + 3 * 2 + 45 + 3 * 2 + 4 Operator precedence evaluates this asOperator precedence evaluates this as5 + (3*2) + 4 = 15 not (5+3) * (2+4) = 48 as intended5 + (3*2) + 4 = 15 not (5+3) * (2+4) = 48 as intended Moral: By convention, enclose each macro argument in Moral: By convention, enclose each macro argument in

parenthesis:parenthesis:#define mult(a,b) (a)*(b)#define mult(a,b) (a)*(b)

Page 140: Introduction to UNIX

UNIX Intro. 140

Nondeterminism in CNondeterminism in C

Library routinesLibrary routines– malloc() returns a nondeterministically-chosen addressmalloc() returns a nondeterministically-chosen address– Address used as a hash key produces nondeterministic Address used as a hash key produces nondeterministic

resultsresults Argument evaluation orderArgument evaluation order

– myfunc( func1(), func2(), func3() )myfunc( func1(), func2(), func3() )– func1, func2, and func3 may be called in any orderfunc1, func2, and func3 may be called in any order

Word sizesWord sizesint a;int a;a = 1 << 16;a = 1 << 16; /* Might be zero *//* Might be zero */a = 1 << 32;a = 1 << 32; /* Might be zero *//* Might be zero */

Page 141: Introduction to UNIX

UNIX Intro. 141

Nondeterminism in CNondeterminism in C

Uninitialized variablesUninitialized variables– Automatic variables may take values from stackAutomatic variables may take values from stack– Global variables left to the whims of the OSGlobal variables left to the whims of the OS

Reading the wrong value from a unionReading the wrong value from a union– union { int a; float b; } u; u.a = 10; printf(“%g”, u.b);union { int a; float b; } u; u.a = 10; printf(“%g”, u.b);

Pointer dereferencePointer dereference– *a undefined unless it points within an allocated array and has *a undefined unless it points within an allocated array and has

been initializedbeen initialized– Very easy to violate these rulesVery easy to violate these rules– Legal: int a[10]; a[-1] = 3; a[10] = 2; a[11] = 5;Legal: int a[10]; a[-1] = 3; a[10] = 2; a[11] = 5;– int *a, *b; a - b only defined if a and b point into the same arrayint *a, *b; a - b only defined if a and b point into the same array

Page 142: Introduction to UNIX

UNIX Intro. 142

Nondeterminism in CNondeterminism in C

How to deal with nondeterminism?How to deal with nondeterminism?– Caveat programmerCaveat programmer

Studiously avoid nondeterministic constructsStudiously avoid nondeterministic constructs– Compilers, lint, etc. don’t really helpCompilers, lint, etc. don’t really help

Philosophy of C: get out of the programmer’s wayPhilosophy of C: get out of the programmer’s way ““C treats you like a consenting adult”C treats you like a consenting adult”

– Created by a systems programmer (Ritchie)Created by a systems programmer (Ritchie) ““Pascal treats you like a misbehaving child”Pascal treats you like a misbehaving child”

– Created by an educator (Wirth)Created by an educator (Wirth) ““Ada treats you like a criminal”Ada treats you like a criminal”

– Created by the Department of DefenseCreated by the Department of Defense

Page 143: Introduction to UNIX

UNIX Intro. 143

SummarySummary

C evolved from the typeless languages BCPL and C evolved from the typeless languages BCPL and BB

Array-of-bytes model of memory permeates the Array-of-bytes model of memory permeates the languagelanguage

Original weak type system strengthened over timeOriginal weak type system strengthened over time C programs built fromC programs built from

– Variable and type declarationsVariable and type declarations– FunctionsFunctions– StatementsStatements– ExpressionsExpressions

Page 144: Introduction to UNIX

UNIX Intro. 144

Summary of C typesSummary of C types

Built from primitive types that match processor typesBuilt from primitive types that match processor types char, int, float, double, pointerschar, int, float, double, pointers Struct and union aggregate heterogeneous objectsStruct and union aggregate heterogeneous objects Arrays build sequences of identical objectsArrays build sequences of identical objects Alignment restrictions ensured by compilerAlignment restrictions ensured by compiler Multidimensional arraysMultidimensional arrays Three storage classesThree storage classes

– global, static (address fixed at compile time)global, static (address fixed at compile time)– automatic (on stack)automatic (on stack)– heap (provided by malloc() and free() library calls)heap (provided by malloc() and free() library calls)

Page 145: Introduction to UNIX

UNIX Intro. 145

Summary of C expressionsSummary of C expressions

Wide variety of operatorsWide variety of operators– Arithmetic + - * /Arithmetic + - * /– Logical && || (lazy)Logical && || (lazy)– Bitwise & |Bitwise & |– Comparison < <=Comparison < <=– Assignment = += *=Assignment = += *=– Increment/decrement ++ --Increment/decrement ++ --– Conditional ? :Conditional ? :

Expressions may have side-effectsExpressions may have side-effects

Page 146: Introduction to UNIX

UNIX Intro. 146

Summary of C statementsSummary of C statements

ExpressionExpression ConditionalConditional

– if-else switchif-else switch IterationIteration

– while do-while for(;;)while do-while for(;;) BranchingBranching

– goto break continue returngoto break continue return

Awkward setjmp, longjmp library routines for non-Awkward setjmp, longjmp library routines for non-local gotolocal goto

Page 147: Introduction to UNIX

UNIX Intro. 147

Summary of CSummary of C

PreprocessorPreprocessor– symbolic constantssymbolic constants

– inline-like functionsinline-like functions

– conditional compilationconditional compilation

– file inclusionfile inclusion

Sources of nondeterminsmSources of nondeterminsm– library functions, evaluation order, variable sizeslibrary functions, evaluation order, variable sizes

Page 148: Introduction to UNIX

UNIX Intro. 148

The Main PointsThe Main Points

Like a high-level assembly languageLike a high-level assembly language

Array-of-cells model of memoryArray-of-cells model of memory

Very efficient code generation follows from close Very efficient code generation follows from close semantic matchsemantic match

Language lets you do just about everythingLanguage lets you do just about everything Very easy to make mistakesVery easy to make mistakes

Page 149: Introduction to UNIX

UNIX Intro. 149

Object Oriented ProgrammingObject Oriented Programming

Page 150: Introduction to UNIX

UNIX Intro. 150

Problem DescriptionProblem Description

“ …“ …customerscustomers are allowed to have different are allowed to have different types of types of bank accountsbank accounts, , depositdeposit moneymoney, , withdrawwithdraw moneymoney and and transfertransfer moneymoney between between accountsaccounts””

Page 151: Introduction to UNIX

UNIX Intro. 151

Procedural ApproachProcedural Approach

bool MakeDeposit(int accountNum,float amount);bool MakeDeposit(int accountNum,float amount);

float Withdraw(int accountNum,float amount);float Withdraw(int accountNum,float amount);

struct Account {struct Account {

char *name;char *name;

int accountNum;int accountNum;

float balance;float balance;

char accountType;char accountType;

};};

Page 152: Introduction to UNIX

UNIX Intro. 152

Procedural Approach cont’dProcedural Approach cont’d

Focus is on proceduresFocus is on procedures All data is shared: no protectionAll data is shared: no protection More difficult to modifyMore difficult to modify Hard to manage complexityHard to manage complexity

Page 153: Introduction to UNIX

UNIX Intro. 153

Procedural vs. Object-OrientedProcedural vs. Object-Oriented

ProceduralProcedural

Withdraw, deposit, transferWithdraw, deposit, transfer

Object OrientedObject Oriented

Customer, money, accountCustomer, money, account

Page 154: Introduction to UNIX

UNIX Intro. 154

Mapping the world to softwareMapping the world to software

Objects in the problem domain are mapped to Objects in the problem domain are mapped to objects in softwareobjects in software

011101

10011

11101

0110100

11010

010101

1110101

10101

Page 155: Introduction to UNIX

UNIX Intro. 155

Object OrientedObject Oriented

Data and operations are grouped togetherData and operations are grouped together

AccountWithdraw

Deposit

Transfer

Interface:

Set of available operations

Page 156: Introduction to UNIX

UNIX Intro. 156

Data EncapsulationData Encapsulation

class Account {

public:

float withdraw();

void deposit(float amount);

private:

float balance;

);

Page 157: Introduction to UNIX

UNIX Intro. 157

Advantages of EncapsulationAdvantages of Encapsulation

ProtectionProtection ConsistencyConsistency Allows changeAllows change

Page 158: Introduction to UNIX

UNIX Intro. 158

Objects and ClassesObjects and Classes

Classes reflect concepts, objects reflect Classes reflect concepts, objects reflect instances that embody those concepts.instances that embody those concepts.

Daria Jane BrittanyJodie

girlclassobject

Page 159: Introduction to UNIX

UNIX Intro. 159

Objects and Classes cont’dObjects and Classes cont’d

A A classclass captures the common properties of captures the common properties of the objects instantiated from itthe objects instantiated from it

A class characterizes the common A class characterizes the common behavior of all the objects that are its behavior of all the objects that are its instancesinstances

Page 160: Introduction to UNIX

UNIX Intro. 160

Objects and Classes cont’dObjects and Classes cont’dClass BankAccountBalanceInterestYTDOwnerAccount_number

Balance 500InterestYTDOwner Account_number

Balance 10,000InterestYTDOwner Account_number

Operations

MakeDesposit

Transfer

WithDraw

GetBalance

Page 161: Introduction to UNIX

UNIX Intro. 161

Objects as instances of ClassesObjects as instances of Classes

The world conceptually consists of objectsThe world conceptually consists of objects Many objects can be said to be of the same type Many objects can be said to be of the same type

or classor class– My bank account, your bank account, Bill Gates’ bank My bank account, your bank account, Bill Gates’ bank

account …account …

We call the object type a class We call the object type a class

Page 162: Introduction to UNIX

UNIX Intro. 162

InstantiationInstantiation

An Object is instantiated from a ClassAn Object is instantiated from a Class

BankAccount myAccount;

myAccount = new BankAccount;

Page 163: Introduction to UNIX

UNIX Intro. 163

Objects and ClassesObjects and Classes

ClassClass– Visible in source codeVisible in source code

– The code is not The code is not duplicatedduplicated

ObjectObject– Own copy of dataOwn copy of data

– Active in running Active in running programprogram

– Occupies memoryOccupies memory

– Has the set of Has the set of operations given in the operations given in the classclass

Page 164: Introduction to UNIX

UNIX Intro. 164

ClassificationClassification

Mammal

Rodent Primate Cats

Reptile

Animal

Squirel RabbitMouse

Page 165: Introduction to UNIX

UNIX Intro. 165

ClassificationClassification

Checking Account

Value First Select Access First Interest

Savings Account

Account

Page 166: Introduction to UNIX

UNIX Intro. 166

InheritanceInheritance

A class which is a subtype of a more A class which is a subtype of a more general class is said to be inherited from it.general class is said to be inherited from it.

The sub-class inherits the base class’ data The sub-class inherits the base class’ data members and member functionsmembers and member functions

Page 167: Introduction to UNIX

UNIX Intro. 167

Inheritance cont’dInheritance cont’d

A sub-class has all data members of its A sub-class has all data members of its base-class plus its ownbase-class plus its own

A sub-class has all member functions of its A sub-class has all member functions of its base class (with changes) plus its ownbase class (with changes) plus its own

Inheritance is meant to implement sub-Inheritance is meant to implement sub-typing (don’t abuse it)typing (don’t abuse it)

Page 168: Introduction to UNIX

UNIX Intro. 168

AbstractionAbstraction

Management of complexityManagement of complexity Hierarchical classification:Hierarchical classification:

is-a relationship: inheritanceis-a relationship: inheritance

has-a relationship: containmenthas-a relationship: containment

Page 169: Introduction to UNIX

UNIX Intro. 169

PolymorphismPolymorphism

One interfaceOne interface Multiple implementationsMultiple implementations InheritanceInheritance Method overloadingMethod overloading

Page 170: Introduction to UNIX

UNIX Intro. 170

What is a good class ?What is a good class ?

A class abstracts objects A class abstracts objects A class should be non-trivial in the context A class should be non-trivial in the context

of the program (has data structures and of the program (has data structures and operations different from other classes)operations different from other classes)

Page 171: Introduction to UNIX

UNIX Intro. 171

SummarySummary

What is Object Oriented Programming?What is Object Oriented Programming? Object-oriented programming is a method Object-oriented programming is a method

of implementation in which programs are of implementation in which programs are organized as cooperative collections of organized as cooperative collections of objects, each of which represents an objects, each of which represents an instance of some class, and whose classes instance of some class, and whose classes are all members of one or more hierarchy of are all members of one or more hierarchy of classes united via inheritance relationshipsclasses united via inheritance relationships