Tải bản đầy đủ - 0 (trang)
Chapter 24. Starting, Stopping, and Killing Processes

Chapter 24. Starting, Stopping, and Killing Processes

Tải bản đầy đủ - 0trang

SummaryBox

We'vealreadytalkedaboutsomanyofthetopicsinthischapter,hereorthere,

thatitmayseemlikearealhodgepodge.It'sagrab-bagofimportantthingsto

knowaboutprocesses—whichyoucanthinkofasprogramsthatareactually

running,ratherthansittingonthedisksomewhere.

Thechapterstartsoutwithacoupleofconceptualarticles.Theydefinesome

importanttermsthatyou'relikelytoencounterinthischapter.

Thenwetalkaboutthepscommand,whichtellsyouwhatprocessesyouhave

runningandjustwhattheyareupto(Section24.5,Section24.6,Section24.8).

Thenextfewarticlescoversignals,whichareonewayprocessescommunicate

withoneanother.Wecovertopicslike:

Whataresignals(Section24.10)?

Howtosendsignalsfromthekeyboard(Section24.11andSection24.12;

alsoseeSection5.8).

Howshellprogramscan"handle"signals(Section24.13andSection

35.17).

Wegofromtheretoamoregeneraldiscussionofwaystokillprocesses:

Howtokillallyourprocesses(Section24.14).

HowtokillprocessesbynameratherthanbyprocessID(Section24.16).

Howtostoprunawayjobs(Section24.17).

Whysomeprocessesdon'tseemtogoawaywhenyoukillthem(Section

24.18,Section24.19).

Howtogetridofafrozenwindow(Section24.22).

Howtomakesureprocessesdon'tdiewhenyoulogout(Section23.10).

—TOR



24.2forkandexec

WediscussforkandexecinSection27.2,buttheconceptcomesupsooftenin

thischapterthatwethoughtweoughttohaveaclosercrossreference.

Putsimply,forkandexecaretheUnixsystemcalls(requestsforoperating

systemservices)thatUnixprogramsusetocreatenewprocesses.Whenyoustart

upaUnixsystem,itstartswithonlyoneprocess,aprogramcalledinit.

Howdoesinitmagicallyturnintothehundredsorperhapseventhousandsof

processesthatmakeupaworkingUnixsystem?That'swhereforkandexec

comein.

Oneprocessspawnsanother("spawn"isanothertermyoushouldgetusedto

seeing)eitherbyreplacingitselfwhenit'sdone—anexec—or,ifitneedsto

stayaround,bymakingacopyofitself—afork.Inthelattercase,theforked

copycommitspolitesuicidebyexecingthedesiredsecondprogram.

AgoodexampleofthiswholesequencecanbeseeninthewayaUnixsystem's

loginprocedureforterminals(non-network(Section1.21)logins)works.The

initprocessspawnsaseriesofgettyprocesses,eachofwhichmonitorsaserial

port(atty),lookingforactivity.It'sthegettyprogramthatactuallyputsupthe

firstlogin:prompt.

Oncesomeoneactuallytypesaloginname,getty'sjobisdone;itexecsthelogin

command.loginpromptsforapassword(iftheaccounthasone)and,ifthe

passwordisokay,execstheloginshell.Wheneveryoustartanotherprogram,the

shellforksitself,andthecopyexecswhateverprogramyouaskedtorun.

That'swhysomecommandsarebuiltintotheshell(Section1.9).There's

overheadinvolvedinstartinganewprocess.What'smore,becauseachild

processcan'taffectitsparent'senvironment(Section24.3),somecommands

don'tmakesenseasseparateprocesses.Forexample,cdmustbebuiltin,orit

couldn'tchangetheworkingdirectoryforthecurrentshell.

There'sanexeccommandthatyoucantypeatashellprompt;seeSection36.5.

Watchout,though:itwillreplaceyourshellwithwhatevercommandyouexec,



withnogoingback.Thisisusefulonlyifyouwanttoreplaceyourshellwith

someotherinteractivecommandinterpreterwithsimilarpowers,orifyou'llbe

readytologoutwhenthecommandyouexecfinishes.

—TOR



24.3ManagingProcesses:OverallConcepts

Asyouknow,whenyoulogintoyourUnixaccountandstarttyping,you're

talkingtotheshell(Section27.1).Theshellyouusemaybeavariantofthe

Bourneshell(suchasastandardsh,ksh,ortheGNUshellbash),orperhapsitis

avariantoftheCshell,csh(suchas,perhaps,thetcshshellthatincludeslineandhistory-editingfeatures).Alternatively,youmaybeusingasomewhatless

commonshellsuchasrc.

Yourshellisaprocess,oneofmanyindividualprogramsrunningatthesame

timeonthemachine.Everyprocesshascertainpiecesofinformationassociated

withit,includingthefollowing:

TheprocessID(PID)isanumberassignedtotheprocesswhenitisstarted

up.ProcessIDsareunique(thatis,theycycleandareeventuallyreused,but

notwoprocesseshavethesameprocessIDatthesametime).

TheuserID(UID)tellswhotheprocessbelongsto.Thisdetermineswhat

filesanddirectoriestheprocessisallowedtoreadfromorwriteto

(Section50.1),aswellaswhoisallowedtokilltheprocess(Section24.12)

(tellittostoprunning).

ThegroupID(GID)issimilartotheuserIDbuttellswhichgroupthe

processbelongsto.Onsomesystems,thiscontrolsthegroupassignedto

filescreatedbytheprocess.SeeSection50.2.

Theenvironmentcontainsalistofvariablenamesandassociatedvalues.

Forexample,whenyoutypeecho$HOMEattheshellanditprintsout

thenameofyourhomedirectory(Section1.15),ithastoldyouthe

contentsoftheenvironmentvariable(Section35.3)calledHOME.



Thecurrentworkingdirectory(Section31.3)isthedirectorythatis

currentlythedefault.Whenyouspecifyafilenametoaprogrambutdonot

sayexplicitlywheretolookforitwithapathname(Section31.2),the

programwilllookinthecurrentworkingdirectory—ifthePATHvariable

containsthecurrentdirectory(Section35.6explains).

Filedescriptorsarearecordofwhichfilesaprocesshasopenedforreading

orwriting,aswellasthecurrentpositionineachfile.

VersionsofUnixwithjobcontrol(Section23.1)haveprocessgroups.A

processgroupisusedfordistributionofsignals(Section24.10,Section

24.11,Section24.14).It'salsousedtocontrolwhichprocesscanreadfrom

aterminal.Aprocessthathasthesameprocessgroupastheterminalis"in

theforeground"andcanreadfromtheterminal.Otherprocessesare

stoppedwhentheytrytoreadfromtheterminal.

Whenyou'retypingcommandsattheshell,itisthecontrollingprocessofyour

terminal,meaningthatit(theshell)istheprocessthatgetstheinputyoutype.

SeeSection24.6.

Normally,whenyoutypeacommandattheshellprompt,thatcommandruns

andisallowedbytheshelltotakeovertheterminalforitslifetime.Forexample,

ifyoutypemore.logintoviewyour.loginfile,theshellstartsupthemore

programandthensitsaroundwaitingforittofinish;whilemoreisrunning,you

cantypecommandstopagethroughthefileandmore(nottheshell)willsee

them.Thecommandyouruniscalledachildorsubprocessoftheshellprocess,

whichisitsparent.Allprocessinformation(userID,groupID,etc.)isinherited

bythechildfromitsparent,exceptfortheprocessID,sincethechildisassigned

anewone.Built-inshellcommands(Section1.9)suchascddon'tstartachild

process.

Althoughthenormalbehaviorisfortheshelltowaituntilanycommandyourun

hasfinishedbeforeitbecomesactiveagain,therearesomesituationsinwhich

youdon'twantthistooccur.Forexample,ifyou'reusingawindowsystemsuch

asX(Section1.22)andwanttostartupanewxtermwindowfromyourshell,

youdon'twanttotypejustxterm,becausethenyouroriginalshellwillwait

untilthextermfinishesbeforeallowingyoutotypeanymorecommands.This



wouldmeanthatyoustillhaveonlyoneshelltoworkin,thusdefeatingthe

purposeofstartingthenewxterm.

Whenyoudon'twantaprocesstofinishbeforegettingbacktotheshell,youcan

runitinthebackground.Youdothisbyputtinganampersand(&)characterat

theendofthecommand,forexample,xterm&.Theshellwillstartthechild

processandthenimmediatelypromptyouforanothercommand.Notethatin

thissituation,theshellretainscontroloftheterminal,andthenewlycreated

backgroundprocesscannotreadinput.Someshellshaveadditionaljobcontrol

(Section23.1)features(processesthatarerunninginthebackgroundareoften

describedasbackgroundjobsorjustjobs)thatenableyoutodothingssuchas

killjobsorbringajobfromthebackgroundintotheforegroundsothatit

becomesthecontrollingprocessoftheterminalandyoucantypeinputatit.

Animportantthingtorememberisthatalthoughprocessinformationisinherited

bychildrenwhentheyarestarted,itisimpossiblefortheparenttoaffectits

child'sprocessinformation(orviceversa)afterthatpoint.Forexample,ifyou

startuptheeditorvi,suspendit(Section24.6),andthenusethecdcommand

intheshelltochangedirectories,viwillstillhavetheoldworkingdirectory

whenyoubringitbackintotheforeground.Similarly,ifyouwriteashellscript

thatchangessomeenvironmentvariables,thosevariableswillcontaintheirold

valuesintheshellwhentheshellscriptexits.ThissometimesconfusesMS-DOS

users,sinceMS-DOSstoresinformationsuchasthecurrentdirectoryinaglobal

areathatisreferencedbyallprograms.Ifitisnecessarytocommunicate

informationfromachildbacktoaparentshell,othermethodsareneeded

(Section24.10,Section35.29).

Onemoreusefulconcept:whenaprocessexits,itreturnsanumericexitstatus

(Section35.12)toitsparentprocess.Byconvention,azerostatusmeans

success;nonzeromeanssomekindoffailure.

Justastherearewaystomodifytheenvironmentandthecurrentworking

directoryoftheshell,therearealsousefulwaystomanipulatefiledescriptors

(Section36.16).

—JIK



24.4Subshells

InUnix,whenaprogramstartsanotherprogram(moreexactly,whenaprocess

startsanotherprocess),thenewprocessrunsasasubprocess(Section24.3)or

childprocess.[1]Whenashellstartsanothershell,thenewshelliscalleda

subshell.[2]

Sowhat?Therearesomeimportantthingstoknowaboutit:thechildprocess

getsacopyofitsparent'senvironment,andanychangesintheenvironmentof

thechildprocessaren'tpassedtoitsparent."Still,"Ihearyousay,"sowhat??"

Shellscriptsareruninasubshell(unlessyouusethesourceor.

commands(Section35.29)tostartthescript).Ifthescriptmakeschanges

totheenvironmentofits(sub)shell,theparentshellwon'tseethose

changes.Ifthescriptusescd,itdoesn'tchangethecurrentdirectoryinthe

parentshell.IfthescriptchangesthevalueoftheTZ(orany)environment

variable,thatwon'tchangeTZintheparentshell.Thescriptcanseta

differentumaskthantheparentshell—noproblem.

Therearetimesyoumightwanttostartasubshellfromyourcurrentshell.

Maybeyouhaveaspecialprojectwhereyouneedtoworkinadifferent

currentdirectory,resetenvironmentvariables,setanewhomedirectory,

resetsomealiases,useadifferentPATH(Section35.6),whatever.When

youendthesubshell,theparentshell'senvironmentwillbethewayitwas.

Ifyourparentshellhasjobcontrol(Section23.3),youcanstopthe

subshellandpopbacktoyourparentshellwithoutlosingthechangesinthe

subshell.Ifthechildshellhasjobcontrol,too,thecommandsuspend(or

kill-STOP$$(Section27.17))willstopit.Otherwise,justtypeCTRL-zat

thesubshell'sprompt.Forexample:



promptSection4.1

myprompt%csh

myprompt%setprompt="project%"

project%cdproject-directory



project%setenvPRINTERplotter

project%setpath=($pathsome-new-directories

project%setenvEXINIT"sets=4sw=4awwm=0"

...dosomework...

project%suspend

Stopped

...backtoparentshell...

myprompt%

myprompt%fg%csh

...backtosubshell...

project%

IusesuspendsomuchthatI'vemadeaCTRL-z-likealiasnamedz:



aliaszsuspend...csh

aliasz=suspend...bash,ksh

Ifyouneedadifferenttypeofshelltemporarily,justtypethatshell'sname

ataprompt.Whenyouendtheshellbytypingexitorbysuspendingit(as

shownabove),you'rebacktoyourusualshell.Forexample,youmight

normallyusebashbutwanttousethezshmultilineeditingforafewloops

youneedtorun.Asanotherexample,Istartedalotofdifferentshellswhile

Iwaswritingthisbook—andsuspendedthem,asabove,whenIwasn't

usingthem.Veryhandy.

Ashellescape(Section17.21)startsasubshell.Dowhateveryouwantto

thesubshell'senvironment.Whenyouendtheshellescape,thechangesgo

away.

Thesucommandstartsasubshell.cdanywhere,changeenvironment

variables,andsoon.

Ifyouusetheexitcommand,asubshell(oranyshell)willterminate.Inascript,

whentheshellreadstheendoffile,thatdoesanimplicitexit.Onthecommand



line,anend-of-inputcharacter(usuallyCTRL-d)willdothesamething.Section

35.16explainshowexitsetsashell'sexitstatus.

—JP



24.5ThepsCommand

Thepscommandvariesfromsystemtosystem.(ThepsononeRedHatLinux

systemreadsaPS_PERSONALITYenvironmentvariablewith21possible

settings!)Thisarticledescribesseveraldifferentversions.Yoursisprobably

differentinsomeways,socheckyourpsmanualpagefordetails.

Thepscommandproducesareportsummarizingexecutionstatisticsforcurrent

processes.ThebarepscommandliststheprocessID,theterminalfromwhich

thecommandwasstarted,howmuchCPUtimeithasused,andthecommand

itself.Theoutputlookssomethinglikethis(itdiffersbysystem):



PIDTTSTATTIMECOMMAND

1803p5IW0:00-csh(csh)

1883p5IW0:04vioutline

1811p6IW0:01-csh(csh)

5353p6TW0:01vi4890

Bydefault,pslistsonlyyourownprocesses.Therearemanytimes,though,

whenit'sdesirabletohaveamorecompletelistingwithalotofdataaboutallof

theprocessescurrentlyrunningonthesystem.Theoptionsrequiredtodothis

differbetweenBSDUnixandSystemV.UnderBSDUnix,thecommandispsaux,whichproducesatableofallprocesses,arrangedinorderofdecreasing

CPUusageatthemomentwhenthepscommandwasexecuted.[The-aoption

givesprocessesbelongingtoallusers,-ugivesamoredetailedlisting,and-x

includesprocessesthatnolongerhaveacontrollingterminal(Section24.6).—

TOR]Itisoftenusefultopipethisoutputtohead(Section12.12),whichwill

displaythemostactiveprocesses:



%ps-aux|head-5

USERPID%CPU%MEMSZRSSTTYSTATTIMECOMMA



martin1292374.222.5223376p5R2:12f77chavez1672510.950.811461826p6RN56:04g94H

ng170263.51.2354240coI0:19vibe

gull79970.20.314246p3S0:04csh

Themeaningsofthefieldsinthisoutput(aswellasothersdisplayedbythe-l

optiontops)aregiveninTable24-1.

ThefirstlineofthisoutputshowsthatusermartinisrunningaFORTRAN

compilation(f77).ThisprocesshasPID(Section24.3)12923andiscurrently

eitherrunningorrunnable.Userchavez'sprocess(PID16725),executingthe

programg94,isalsorunningorrunnable,thoughataloweredpriority.Fromthis

display,it'sobviouswhoisusingmostsystemresourcesatthisinstant:martin

andchavezhaveabout85%oftheCPUand73%ofthememorybetweenthem.

However,althoughitdoesdisplaytotalCPUtime,psdoesnotaveragethe

%CPUor%MEMvaluesovertimeinanyway.

Table24-1.pscommandoutputfields

Column[3]



Contents



USER(BSD)



Usernameofprocessowner



UID(SystemV)



UserID(Section24.3)ofprocessowner



PID



ProcessID



%CPU



EstimatedfractionofCPUconsumed(BSD)



%MEM



Estimatedfractionofsystemmemoryconsumed(BSD)



SZ



VirtualmemoryusedinK(BSD)orpages(SystemV)



RSS



Realmemoryused(insameunitsasSZ)



TT,TTY



Terminalportassociatedwithprocess



STAT(BSD),S

(SystemV)



Currentprocessstate;one(ormoreunderBSD)of:







R:Runningorrunnable







S:Sleeping







I:Idle(BSD);intermediatestate(SystemV)







T:Stopped(Section23.1)







Z:Zombieprocess(Section24.19)







D(BSD):Diskwait







P(BSD):Pagewait







X(SystemV):Growing,waitingformemory







K(AIX):Availablekernelprocess







W(BSD):Swappedout







N(BSD):Niced(Section26.5,Section26.7),executionpriority

lowered







>(BSD):Executionpriorityartificiallyraised(Section26.7)



TIME



TotalCPUtimeused



COMMAND



Commandlinebeingexecuted(maybetruncated)



STIME(SystemV) Timeordateprocessstarted



C(SystemV),CP

(BSD)



ShorttermCPU-usefactor;usedbyschedulerforcomputing

executionpriority(PRIbelow)



F



Flagsassociatedwithprocess(seepsmanualpage)



PPID



Parent'sPID



PRI



Actualexecutionpriority(recomputeddynamically)



NI



Processnicenumber(Section26.5)



WCHAN



Eventprocessiswaitingfor



AvaguelysimilarlistingisproducedbytheSystemVps-efcommand:



$ps-ef

UIDPIDPPIDCSTIMETTYTIMECMD

root00009:36:35?0:00sched

root10009:36:35?0:02/etc/init

...

gull799711009:49:32ttyp30:04csh



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 24. Starting, Stopping, and Killing Processes

Tải bản đầy đủ ngay(0 tr)

×