P rograms vs P rocesses A pr ogr am is passive 3: P rocesses - - PDF document

p rograms vs p rocesses
SMART_READER_LITE
LIVE PREVIEW

P rograms vs P rocesses A pr ogr am is passive 3: P rocesses - - PDF document

P rograms vs P rocesses A pr ogr am is passive 3: P rocesses Sequence of commands wait ing t o be r un A pr ocess is act ive An inst ance of pr ogr am being execut ed Last Modif ied: Ther e may be many pr ocesses r unning


slide-1
SLIDE 1

1

  • 1

3: P rocesses

Last Modif ied: 6/ 1/ 2004 11:53:05 AM

  • 2

P rograms vs P rocesses

A pr ogr am is passive

Sequence of commands wait ing t o be r un

A pr ocess is act ive

An inst ance of pr ogr am being execut ed Ther e may be many pr ocesses r unning t he same

pr ogr am

Also called j ob or t ask

  • 3

What makes up a process?

Address space Code Data St ack (nest ing of procedure calls made) Regist er values (including t he PC) Resources allocat ed t o t he process

Memor y, open f iles, net wor k connect ions

  • 4

Address Space Map

St ack

(Space f or local var iables et c. For each nest ed pr ocedur e call)

Heap

(Space f or memor y dynamically allocat ed e.g. wit h malloc)

St at ically declar ed var iables

(Global var iables)

Code

(Text Segment )

St ack Point er PC Ox0000 Biggest Vir t ual Address Somet imes Reserved f or OS Somet imes Reserved f or Error Cat ching

  • 5

What kinds of processes are t here?

Comput e bound/ I O bound Long-running/ short-r unning I nt eract ive/ bat ch Large/ small memory f oot print Cooperat ing wit h ot her processes? … How does t he OS cat egorize processes?

  • 6

P rocess St at es

During t heir lif et ime, processes move

bet ween various st at es

Ready – wait ing f or a t ur n t o use t he CPU Running – cur r ent ly execut ing on t he CPU

  • How many processes can be in t his st at e?

Wait ing – Unable t o use t he CPU because

blocked wait ing f or an event

Ter minat ed/ Zombie – Finished execut ing but

st at e maint ained unt il par ent pr ocess r et r ieves st at e

slide-2
SLIDE 2

2

  • 7

St at e Transit ions

New Ready Running Terminat ed Wait ing

Schedule/ unschedule Request Resource

  • r Service

Gr ant Resour ce

  • 8

St at e Queues

OSes of t en maint ain a number of queues of

processes t hat represent t he st at e of t he processes

All t he r unnable pr ocesses ar e linked t oget her

int o one queue

All t he pr ocesses blocked (or per haps blocked

f or a par t icular class of event ) ar e linked t oget her

As a pr ocess changes st at e, it is unlinked f r om

  • ne queue and linked int o anot her
  • 9

Cont ext Swit ch

When a process is running, some of it s

st at e is st ored direct ly in t he CPU (regist er values, et c.)

When t he OS st ops a process, it must save

all of t his hardware st at e somewhere (PCB) so t hat it can be r est or ed again

The act of saving one processes hardware

st at e and rest oring anot her’s is called a cont ext swit ch

100s or 1000s per second!

  • 10

Cont ext Swit ch

  • 11

Schedulers

Long-t erm scheduler (or j ob scheduler) –

select s which processes should be brought int o t he ready queue.

Short-t erm scheduler (or CPU scheduler) –

select s which process should be execut ed next and allocat es CPU.

  • 12

Schedulers (cont )

Shor t-t er m scheduler is invoked ver y f r equent ly

(milliseconds) ⇒ (must be f ast ).

Long-t er m scheduler is invoked ver y inf r equent ly

(seconds, minut es) ⇒ (may be slow).

The long-t er m scheduler cont r ols t he degr ee of

mult ipr ogr amming.

Pr ocesses can be descr ibed as eit her :

I / O- bound process – spends more t ime doing I / O t han

comput at ions, many short CP U burst s.

CPU-bound process – spends more t ime doing

comput at ions; f ew very long CP U burst s.

slide-3
SLIDE 3

3

  • 13

Family Tree

Age old quest ions – wher e do new pr ocesses come

f rom?

New pr ocesses ar e cr eat ed when an exist ing

pr ocess r equest s it

Creat ing process called t he parent ; creat ed called t he

child

Children of same parent called siblings

Childr en of t en inher it pr ivileges/ at t r ibut es f r om

t heir parent

Working direct ory, Clone of address space

When child is cr eat ed, par ent may eit her wait f or

it or cont inue in par allel

  • 14

pst ree

init - +- 1 8*[ Xvnc] | - amd | - at d | - bdf lush | - crond | - 1 6*[ deskguide_apple] | - 8*[ gconf d- 1] | - gedit | - 18*[gnome- name- serv] | - 16*[gnome- session] | - 16*[gnome- smproxy] | - gnome- t erminal- +- csh---gt op | ` - gnome- pt y- helpe | - gnome- t erminal- +- csh- +

  • gt op

| | ` - t csh | ` - gnome- pt y- helpe | - gnome- t erminal- +- csh---t csh--- xt erm- - - csh | ` - gnome- pt y- helpe | - gpm | - 8*[hyperbola] | - kevent d | - khubd | - 5*[ kj ournald] | - klogd | - ksof t irqd_CP U0 | - ksof t irqd_CPU1 | - kswapd | - kupdat ed | - lockd init - +- 1 8*[ Xvnc] | - 1 6*[ magicdev] | - mdrecoveryd | - migrat ion_CP U0 | - migrat ion_CP U1 | - 6*[ minget t y] | - 2*[naut ilus- - - naut ilus

  • - - 8*[nautilus]]

| - 2*[naut ilus- - - naut ilus

  • - -10*[naut ilus]]

| - 3*[naut ilus- - - naut ilus

  • - - 9*[nautilus]]

| - naut ilus- - - naut ilus---7*[naut ilus] | - 7*[naut ilus- hist or] | - naut ilus- mozill- - - naut ilus

  • mozill- - - 4*[naut ilus-

mozill] | - 8*[naut ilus- news] | - 8*[naut ilus- not es] | - 7*[naut ilus- t hrobb] | - nt pd | - 1 3*[ oaf d] | - 16*[panel] | - port map | - 1 6*[ rhn- applet ] | - rhn- applet - - - gnome_segv | - rhnsd | - rpc.st at d | - rpciod | - 14*[sawf ish] | - 2*[sawf ish- - -rep] | - scsi_eh_0 | - scsi_eh_1 | - sendmail init - +- 1 8*[ Xvnc] | - sshd- +- 2*[ sshd--- csh--- mc] | | - sshd- - - csh | | - sshd- - - csh- +- more | | ` - net st at | `-sshd---csh ---pst r ee | - syslogd | - 1 6*[ t asklist _applet ] | - xemacs | - xf s- - - xf s | - xinet d- - - f am | - xscreensaver- - - greynet ic | - xscreensaver- - - hopalong | - 2*[ xscreensaver- - - xscreensaver] | - xscreensaver- - - kumppa | - xscreensaver- - - spot light | - xscreensaver- - - spiral | - xscreensaver- - - nerverot | - xscreensaver- - - st range | - xscreensaver- - - f lame | - xscreensaver- - - grav | - xscreensaver- - - light ning | - xscreensaver- - - penet rat e | - xscreensaver- - - rot zoomer---xscreensaver- ge | - xscreensaver- - - deluxe | - xscreensaver- - - rd- bomb | - xscreensaver- - - sonar | - xscreensaver- - - moire2 ` - ypbind- - - ypbind- - - 2*[ ypbind

  • 15

I nit process

I n last st age of boot pr ocess, ker nel cr eat es a

user level pr ocess, init

I nit is t he par ent (or gr andpar ent …

) of all ot her pr ocesses

I nit does var ious impor t ant housecleaning

act ivit ies

checks and mount s t he f ilesyst ems, set s host name,

t imezones, et c. I nit r eads var ious “r esour ce conf igur at ion f iles”

(/ et c/ rc.conf , et c) and spawns of f pr ocesses t o pr ovide var ious ser vices

I n mult i -user mode, init maint ains processes f or

each t er minal por t ( tty )

Usually runs get t y which execut es t he login program

  • 16

How is a process represent ed?

Usually a process or t ask obj ect Process Cont rol Block When not running how does t he OS

remember everyt hing needed t o st art t his j ob r unning again

Regist er s, St at ist ics, Wor king dir ect or y, Open

f iles, User who owns pr ocess, Timer s, Par ent Pr ocess and sibling pr ocess ids I n Linux, t ask_st ruct def ined in

include/ linux/ sched.h

  • 17

struct task_struct { /* these are hardcoded- don't touch */ volatile long state; /*

  • 1 unrunnable, 0runnable, >0

stopped */ long counter; long priority; unsigned long signal; unsigned long blocked; /* bitmap of masked signals */ unsigned long flags; /* per process flags, defined below */ int errno; long debugreg[8]; /* Hardware debugging registers */ struct exec_domain *exec_domain; /* various fields */ struct linux_binfmt*binfmt; struct task_struct *next_task, * prev_task; struct task_struct *next_run, * prev_run; unsigned long saved_kernel_stack; unsigned long kernel_stack_page; int exit_code, exit_signal; /* ??? */ unsigned long personality; int dumpable :1; int did_exec:1; /* shouldn't this be pid _t? */ int pid; int pgrp; int tty_old_pgrp; int session; /* boolean value for session group leader */ int leader; int groups[NGROUPS]; /* * pointers to (original) parent process, youngest child, younger sibling, * older sibling,

  • respectively. (p ->father can be replaced with * p-

>p_pptr ->pid ) */ struct task_struct *p_opptr, *p_ pptr, *p_cptr , *p_ysptr, *p_osptr; struct wait_queue *wait_chldexit; /* for wait4() */ unsigned short uid,euid ,suid,fsuid; unsigned short gid,egid ,sgid,fsgid; unsigned long timeout, policy, rt_priority; unsigned long it_real_value, it_prof_value, it_virt_value; unsigned long it_real_incr , it_prof_incr, it_virt_incr; struct timer_list real_timer; long utime, stime , cutime, cstime , start_time; /* mm fault and swap info: this can arguably be seen as either mm-specific or thread -specific */ unsigned long min_flt, maj_flt, nswap, cmin_flt, cmaj_flt, cnswap; int swappable:1; unsigned long swap_address; unsigned long old_maj_ flt; /* old value of maj_flt */ unsigned long dec_flt; /* page fault count of the last time */ unsigned long swap_cnt; /* number of pages to swap on next pass */ /* limits */ struct rlimit rlim[RLIM_NLIMITS]; unsigned short used_math; char comm[16]; /* file system info */ int link_count; struct tty_struct *tty; /* NULL if no tty */ /* ipc stuff */ struct sem_undo * semundo ; struct sem_queue *semsleeping; /* ldt for this task - used by Wine. If NULL, default_ldt is used */ struct desc_struct *ldt; /* tss for this task */ struct thread_struct tss; /* filesystem information */ struct fs_struct *fs; /* open file information */ struct files_struct *files; /* memory management info */ struct mm_struct *mm; /* signal handlers */ struct signal_struct *sig; #ifdef __SMP__ int processor; int last_processor; int lock_depth; /* Lock depth. We can context switch in and out of holding asyscall kernel lock... */ #endif };

  • 18

Management of P CBs

PCBs ar e dat a st r uct ur es (j ust like you ar e used t o

at user level)

Space f or t hem may be dynamically allocat ed as

needed or per haps a f ixed sized ar r ay of PCBs f or t he maximum number of possible pr ocesses is allocat ed at init t ime

As pr ocess is cr eat ed, a PCB is assigned and

init ialized f or it

Of t en process id is an of f set int o an array of P

CBs Af t er pr ocess t er minat es, PCB is f r eed

(somet imes kept ar ound f or par ent t o r et r ieve it s exit st at us)

slide-4
SLIDE 4

4

  • 19

St at e Queues

Tail pt r Head pt r Pr ev next Rest of P CB Pr ev next Rest of P CB Pr ev next Rest of P CB Ready queue, queues per device, queue of all pr ocesses, …

  • 20

Cont ext Swit ch

When a pr ocess is r unning, some of it s st at e is

st or ed dir ect ly in t he CPU (r egist er values, et c.)

When t he OS st ops a process, it must save all of

t his hardware st at e somewhere (PCB) so t hat it can be r est or ed again

The act of saving one pr ocesses har dwar e st at e

and r est or ing anot her ’s is called a cont ext swit ch

100s or 1000s per second!

  • 21

UNI X process creat ion

Fork() syst em call

Cr eat es a new PCB and a new addr ess space I nit ializes t he new addr ess space wit h a * copy*

  • f t he par ent ’s addr ess space

I nit ializes many ot her r esour ces t o copies of

t he par ent s (e.g. same open f iles)

Places new pr ocess on t he queue of r unnable

pr ocesses Fork() ret urns t wice: t o parent and child

Ret ur ns child’s pr ocess I D t o t he par ent Ret ur ns 0 t o t he child

  • 22

Example Code Snippet

int main (int argc, char **argv) { int childPid; childPid = fork(); if (childPid == 0){ printf(“Child running\n”); } else { printf(“Parent running: my child is %d\n”, childPid); } }

  • 23

Out put

%./tryfork Parent running: my child is 707 Child running %

  • 24

Experiment s

Tr y put t ing an inf init e loop in t he child’s por t ion (

do you r et ur n t o t he command shell?) and t hen looking f or it in t he ps out put

Tr y put t ing an inf init e loop in t he par ent ’s por t ion

(do you r et ur n t o t he command shell?)

Put an inf init e loop in bot h

t ry killing t he child (look in t he ps out put f or t he child

and t he parent )

Try killing t he parent – what happens t o t he child?

WARNI NG: DO NOT PUT THE FORK COMMAND

I TSELF I N AN I NFI NI TE LOOP!!! YOU WI LL CRASH THE SYSTEM!

slide-5
SLIDE 5

5

  • 25

Fork and Exec

How do we get a br and new pr ocess not j ust a copy

  • f t he parent ?

Exec () syst em call int exec (char * prog, char ** argv)

Exec:

St ops t he current process Loads t he program, prog, int o t he address space P

asses t he argument s specif ied in argv

P

laces t he P CB back on t he ready queue Exec “t akes over ” t he pr ocess

There is no going back t o it when it ret urns Try t o exec somet hing in your shell (example: exec ls) –

when ls is done your shell is gone because ls replaced it !

  • 26

UNI X Shell

int main (int argc, char **argv) { while (1){ int childPid; char * cmdLine = readCommandLine(); if (userChooseExit(cmdLine)){ wait for all background jobs } childPid = fork(); if (childPid == 0){ setSTDOUT _STDIN_STDERR(cmdLine); exec ( getCommand (cmdLine )); } else { if (runInForeground(cmdLine)){ wait ( childPid); } } }

  • 27

Windows P rocess Creat ion

BOOL CreateProcess( LPCTSTR lpApplicationName, // name of executable module LPTSTR lpCommandLine, // command line string LPSECURITY_ATTRIBUTES lpProcessAttributes, // SD LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD BOOL bInheritHandles, // handle inheritance option DWORD dwCreationFlags, // creation flags LPVOID lpEnvironment, // new environment block LPCTSTR lpCurrentDirectory, // current directory name LPSTARTUPINFO lpStartupInfo, // startup information LPPROCESS_INFORMATION lpProcessInformation // process information );

  • 28

Windows vs Unix

Windows doesn’t maint ain t he same

relat ionship bet ween parent and child

Lat er ver sions of Windows have concept of

“j ob” t o mir r or UNI X not ion of par ent and childr en (pr ocess gr oups) Wait ing f or a process t o complet e?

Wait f or SingleObj ect t o wait f or complet ion Get Exit CodePr ocess ( will r et ur n STI LL_ALI VE

unt il pr ocess has t er minat ed)

  • 29

Cooperat ing P rocesses

Pr ocesses can r un independent ly of each ot her or

pr ocesses can coor dinat e t heir act ivit ies wit h

  • t her pr ocesses

To cooper at e, pr ocesses must use OS f acilit ies t o

communicat e

One example: parent process wait s f or child Many ot hers

  • Shared Memory
  • Files
  • Socket s
  • Pipes
  • Signals
  • Event s
  • Remot e Pr ocedur e Call
  • 30

Socket s

A socket is an end-point f or communicat ion

  • ver t he net work

Creat e a socket

int socket(int domain, int type, int

protocol)

Type = SOCK_STREAM f or TCP

Read and wr it e socket j ust like f iles Can be used f or communicat ion bet ween

t wo processes on same machine or over t he net work

slide-6
SLIDE 6

6

  • 31

P ipes

Bi-direct ional dat a channel bet ween t wo

processes on t he same machine

Creat ed wit h:

int pipe (int fildes[2])

Read and wr it e like f iles

  • 32

Signals

Pr ocesses can r egist er t o handle signals wit h t he

signal f unct ion

void signal (int signum, void (*proc) (int))

Pr ocesses can send signals wit h t he kill f unct ion

kill (pid, signum)

Syst em def ined signals like SI GHUP (0), SI GKI LL

(9), SI GSEGV(11)

I n UNI X shell, t ry:

“kill –9 pidOf P rocessYouDon’t ReallyCareAbout ” Signals not used by syst em like SI GUSR1 and

SI GUSR2

Not e: sigsend/ sigact ion similar t o kill/ signal

  • 33

Remot e P rocedure Call (RP C)

  • 34

P rocesses

What is a process? P

rocess St at es

Swit ching Bet ween P

rocesses

Process Creat ion PCBs Communicat ion/ Cooperat ion bet ween

processes

  • 35

Out t akes

Could spend more t ime on t hings in Process

Creat ion and Signal chapt er of St evens