linux環(huán)境高級編程3-unix進(jìn)程環(huán)境、進(jìn)程控制和進(jìn)程關(guān)系_第1頁
linux環(huán)境高級編程3-unix進(jìn)程環(huán)境、進(jìn)程控制和進(jìn)程關(guān)系_第2頁
linux環(huán)境高級編程3-unix進(jìn)程環(huán)境、進(jìn)程控制和進(jìn)程關(guān)系_第3頁
linux環(huán)境高級編程3-unix進(jìn)程環(huán)境、進(jìn)程控制和進(jìn)程關(guān)系_第4頁
linux環(huán)境高級編程3-unix進(jìn)程環(huán)境、進(jìn)程控制和進(jìn)程關(guān)系_第5頁
已閱讀5頁,還剩60頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

第三講:UNIX進(jìn)程環(huán)境、進(jìn)程控制和進(jìn)程關(guān)系段翰聰,李林ComputerScienceofUESTC1精選PPTContentsProcessstatustransitiondiagramProcessstartandterminationCreateandterminateprocessRaceconditionProcessrelationship2精選PPTProcessstatus127943658返回到用戶態(tài)被搶先創(chuàng)建fork內(nèi)存不足僅在對換系統(tǒng)中內(nèi)存足夠就緒且換出喚醒睡眠且換出在內(nèi)存中睡眠喚醒在內(nèi)存中就緒換入換出換出睡眠重新調(diào)度進(jìn)程搶先核心態(tài)運(yùn)行返回系統(tǒng)調(diào)用中斷用戶態(tài)運(yùn)行僵死退出中斷、中斷返回3精選PPTLinux的進(jìn)程組織Proc1Proc1Proc1Proc1Proc1進(jìn)程的物理組織結(jié)構(gòu)CurrentP1P1P1P1P1P1P1P1進(jìn)程的邏輯組織結(jié)構(gòu)4精選PPT5精選PPTLinux的進(jìn)程結(jié)構(gòu)6精選PPTLinux的進(jìn)程結(jié)構(gòu)mmtask_structcountpgdmmapmmap_avlmmap_semmm_structvm_endvm_startvm_flagsvm_inodevm_opsvm_nextdatacodevm_endvm_startvm_flagsvm_inodevm_opsvm_nextvm_area_structvm_area_structprocessvirtualMemory7精選PPTLinux的進(jìn)程結(jié)構(gòu)fsfilestask_structcountumask*root*pwdcountclose_on_execopen_fsfd[0]fd[1]……f_modef_pcsf_flagsf_countf_ownerfd[255]f_inodef_opf_versionfs_structinodeinodeinodefiles_structfilefileoperationroutines8精選PPTProcessstartACprogramstartsexecutionwithafunctionmain.WhenaCprogramisstartedbythekernel,aspecialstart-uproutineiscalledbeforemainfunctioniscalled,whichobtainsaddressofmainandargumentsfrommain.Itwouldcopytheseinformationtou-areaofprocesscontrolblock.

intmain(intargc,char*argv[]);9精選PPTCommand-lineargumentsintmain(intargc,char**argv){inti;printf("argumentnumberis%d\n",argc);for(i=0;i<argc;i++)printf("argv[%d]:%s\n",i,argv[i]);exit(0);}10精選PPTProcessterminationTherearefivewaysforprocesstoterminateNormalterminationReturnfrommain;CallingexitCalling_exitAbnormalterminationCallingabort;Terminatedbyasignal.11精選PPTexitand_exitFunctionvoidexit(intstatus);/*<stdlib.h>*/void_exit(intstatus);/*<unistd.h>*/Twofunctionsterminateaprogramnormally:_exit,whichreturnstothekernelimmediately,andexitwhichperformscertaincleanupprocessingandthenreturnstothekernel.TheexitfunctionhasalwaysperformsacleanshutdownofthestandardI/Olibrary:thefclosefunctioniscalledforallopenstream.Thiscausesallbufferedoutputdatatobeflushed.12精選PPTatexitFunction#include<stdlib.h>intatexit(void(*func)(void));Inton_exit(void(*func)(int,void*),void*arg);WithANSICaprocesscanregisterupto32functionsthatareautomaticallycalledbyexit.Theseareregisteredbyatexitoron_exitfunctionTheexitfunctioncallsthesefunctionsinreverseorderoftheirregistration.13精選PPTExample:(showtime.c)#include<limits.h>#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/times.h>staticvoidshowtimes(void){doubleticks;structtmstinfo;if((ticks=(double)sysconf(_SC_CLK_TCK))==-1)perror("Failedtodetermineclocktickspersecond");elseif(times(&tinfo)==(clock_t)-1)perror("Failedtogettimesinformation");else{

fprintf(stderr,"Usertime:%8.3fseconds\n",tinfo.tms_utime/ticks);fprintf(stderr,"Systemtime:%8.3fseconds\n",tinfo.tms_stime/ticks);fprintf(stderr,"childutime:%8.3fseconds\n",tinfo.tms_cutime/ticks);fprintf(stderr,"Childsystime:%8.3fseconds\n",tinfo.tms_cstime/ticks);}}intmain(void){if(atexit(showtimes)){fprintf(stderr,"Failedtoinstallshowtimesexithandler\n");return1;}return0;}14精選PPTHowaCprogramisstartedandterminatesKernelexitfunc.UserfunctionmainfunctionCstart-uproutineregisterFun.registerFun.StandardI/Ocleanup_exitexitdoesn’treturnexeccallcallreturncallreturncallreturnUserprocess_exit_exitexitdoesn’treturnexitdoesn’treturncallreturnreturn15精選PPTMemorylayoutofaProgramHistorically,aCprogramhasbeencomposedofthefollowingpieces:Textsegment:ThisisthemachineinstructionsthatareexecutedbytheCPU.Itisshareable.Initializeddatasegment.Itcontainsvariablesthatarespecificallyinitializedintheprogram.E.g.:intmaxcount=99;Uninitializeddatasegment.Itisoftencalledthe‘bss’segment.Datainthissegmentisinitializedbythekernelto0orNULLpointerbeforetheprogramstartexecuting:longsum[1000];Stack.Thisiswhereautomaticvariablearestored,alongwithinformationthatissavedeachtimeafunctioniscalled.Heap.Dynamicmemoryallocationtakesplaceontheheap.16精選PPTTypicalmemoryarrangementCommand-lineargumentandEnvironmentvariablesstackheapUninitializeddata(bss)Initializeddatatextinitializedto0orNULLbyexecreadfromprogramfilebyexecHighaddressLowaddress17精選PPTMemoryallocation#include<stdlib.h> #include<alloca.h>void*calloc(size_tnmemb,size_tsize); void*alloca(size_tsize);void*malloc(size_tsize);void*realloc(void*ptr,size_tsize);voidfree(void*ptr);

calloc.Allocatesspaceforaspecifiednumberofobjectofaspecifiedsize.Thespaceisinitializedtoall0bits.malloc.Allocatesaspecifiednumberofbytesofmemory,theinitialvalueofthememoryisindeterminate.realloc.Changesthesizeofapreviouslyallocatedarea.Theabovethreeallocationcallsbrk,whichallocatesmemoryfromheap.Butalloca<alloca.h>functionallocatesmemoryinthestackframeofthecaller.Thistemporaryspaceisautomaticallyfreed18精選PPTEnvironmentvariablesTheenvironmentvariablesareusuallyoftheform‘name=value’.Theirinterpretationisuptothevariousapplications.Wecanhandleenvironmentvariablesthroughfollowingfunctions.#include<stdlib.h>char*getenv(constchar*name);intputenv(constchar*str);/*strlike“name=string”*/intsetenv(constchar*name,constchar*value,intrewrite);voidunsetenv(constchar*name);19精選PPTEnvironmentvariables(Cont.)Thegetenvfunctionreturnsapointertothevalueofaname=valuestring.Theputenvtakesastringoftheformname=valueandplaceitintheenvironmentlist.IFthenamealreadyexists,itsoldvaluewasdisplaced.The

setenvsetsnametovalue.Ifnameexists,then(a)ifrewriteisnonzero,theoldvaluewasdisplaced.(b)ifrewriteis0,nothingoccurs.20精選PPTResourcelimitsEveryprocesshasasetofresourcelimits,someofwhichcanbequireandchangedbyfollowingfunctions.#include<sys/time.h>#include<sys/resource.h>intgetrlimit(intresource,structrlimit*rlptr);intsetrlimit(intresource,conststructrlimit*rlptr);

structrlimit{ rlim_trlim_cur;/*softlimit:currentlimit*/ rlim_trlim_max;/*hardlimit:maximumvalueforrlim_cur*/}21精選PPTResourcelimits(Cont.)resourcemustbeoneof:RLIMIT_CPU.CPUtimelimitinseconds.Whentheprocessreachesthesoftlimit,itissentaSIGXCPUsignal.RLIMIT_DATA.Themaximumsizeoftheprocessdatasegment(initializeddata,uninitializeddata,andheap).RLIMIT_FSIZE.Themaximumsizeoffilesthattheprocessmaycreate.AttemptstoextendafilebeyondthislimitresultindeliveryofaSIGXFSZsignal.RLIMIT_LOCKS.Alimitonthecombinednumberofflock()locksandfcntl()leasesthatthisprocessmayestablish(Linux2.4andlater).22精選PPTResourcelimits(Cont.)

RLIMIT_MEMLOCK.ThemaximumnumberofbytesofvirtualmemorythatmaybelockedintoRAMusingmlock()andmlockall().

RLIMIT_NOFILE.Specifiesavalueonegreaterthanthemaximumfiledescriptornumberthatcanbeopenedbythisprocess.RLIMIT_NPROC.ThemaximumnumberofprocessesthatcanbecreatedfortherealuserIDofthecallingprocess.RLIMIT_STACK.Themaximumsizeoftheprocessstack,inbytes.Uponreachingthislimit,aSIGSEGVsignalisgenerated.Etc.23精選PPTResourcelimitationThreerulesgovernthechangingoftheresourcelimits:Asoftlimitcanbechangedbyanyprocesstoavaluelessthanorequaltoitshardlimit.Anyprocesscanloweritshardlimittoavaluegreaterthanorequaltoitssoftlimits.Thisisirreversiblefornormalusers.Onlysuperuserprocesscanraiseahardlimit.24精選PPTGetrlimit.cLinuxSolaris25精選PPTgetrusageFunction#include<sys/resource.h>intgetrusage(intwho,structrusage*usage);Getrusagefunctionreturnsthecurrentresourceusages,forawhoofeitherRUSAGE_SELForRUSAGE_CHILDREN.Theformerasksforresourcesusedbythecurrentprocess,thelatterforresourcesusedbythoseofitschildrenthathaveterminatedandhavebeenwaitedfor. structrusage{structtimevalru_utime;/*usertimeused*/structtimevalru_stime;/*systemtimeused*/…… }26精選PPTProcessidentifiersEveryprocesshassomeidentifiers,suchasuniqueprocessID.Allprocessesinsystemformaprocesstrees.Generally,eachprocesshasonlyoneparent.

pid_tgetpid(void); 返回:調(diào)用進(jìn)程的進(jìn)程IDpid_tgetppid(void); 返回:調(diào)用進(jìn)程的父進(jìn)程IDpid_tgetuid(void); 返回:調(diào)用進(jìn)程的實(shí)際用戶IDpid_tgeteuid(void); 返回:調(diào)用進(jìn)程的有效用戶IDgid_tgetgid(void); 返回:調(diào)用進(jìn)程的實(shí)際組IDgid_tgetegid(void); 返回:調(diào)用進(jìn)程的有效組ID27精選PPTProcessidentifiers(cont.)Therearesomespecialprocesses.IntraditionUnixsystem,processID0isusuallytheschedulerprocessandifoftenknownastheswapper.ProcessID1isusuallytheinitprocess.ProcessID2isthepagedaemon.ButinLinuxsystem,somethingischanging.28精選PPTLinuxSolaris29精選PPTforkFunction

pid_tfork(void);TheonlywayanewprocessiscreatedbytheLinuxkerneliswhenanexistingprocesscalltheforkfunction.Thisfunctioniscalledoncebutreturnstwice.ThereturnvalueintheparentistheprocessIDofthenewchildwhilethereturnvalueinthechildis0.(why?)Boththechildandparentcontinueexecutingwiththeinstructionthatfollowsthecalltofork.Thechildgetsacopyoftheparent’sdataspace,heap,andstack(exceptlittleinformation)(Copy-on-write).Ingeneral,weneverknowifthechildstartsexecutingbeforetheparentorviceversa.(盡管Linux內(nèi)核會有意選擇子進(jìn)程首先執(zhí)行)30精選PPTstructtask_structunsignedlongstate;intprio;structtask_struct*parent;structlist_headtask;pid_tpid;……進(jìn)程描述符(processdescriptor)structtask_structunsignedlongstate;intprio;structtask_struct*parent;structlist_headtask;pid_tpid;……structtask_structunsignedlongstate;intprio;structtask_struct*parent;structlist_headtask;pid_tpid;……structtask_structunsignedlongstate;intprio;structtask_struct*parent;structlist_headtask;pid_tpid;……任務(wù)鏈表進(jìn)程描述符31精選PPTcopy_process()fork函數(shù)工作調(diào)用dup_task_struct為新進(jìn)程創(chuàng)建一個(gè)內(nèi)核棧;檢查當(dāng)前用戶擁有的進(jìn)程數(shù)是否超出配額;子進(jìn)程狀態(tài)設(shè)置為TASK_UNINTERRUPTIBLE;調(diào)用copy_flags()更新flags成員;調(diào)用get_pid()為新進(jìn)程獲取一個(gè)有效的PID;根據(jù)傳遞給clone()的參數(shù)標(biāo)志,拷貝或共享打開的文件、文件系統(tǒng)信息、信號處理函數(shù)、進(jìn)程地址空間和命名空間等;讓父子進(jìn)程平分剩余的時(shí)間片;最后,作掃尾工作并返回一個(gè)指向子進(jìn)程的指針fork()clone()do_fork()32精選PPTDifferencebetweenparentandchildafterforkPropertiesinheritedfromparent:Realuser/groupID,effectiveuser/groupIDSupplementarygroupIDProcessgroupIDSessionID;Controlterminal.Set-user/group-IDcurrentworkdirectoryFilemodemaskSignalmask;environment;ResourcelimitsDifferencebetweenparentandchild:returnvaluefromforkProcessIDParentprocessID;Thechild’svaluefortms_utime,tms_stime,tms_cutime,tms_ustimearesetto0;FilelocksdonotbeinheritedbychildPendingalarmareclearedforchild33精選PPTintglob=6;/*externalvariableininitializeddata*/charbuf[]="awritetostdout\n";intmain(void){intvar;/*automaticvariableonthestack*/pid_tpid;var=88;if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1)err_sys("writeerror");printf("beforefork\n");/*wedon'tflushstdout*/if((pid=fork())<0)err_sys("forkerror");elseif(pid==0){/*child*/glob++;/*modifyvariables*/var++;}elsesleep(2);/*parent*/printf("pid=%d,glob=%d,var=%d\n",getpid(),glob,var);exit(0);}write

hasnotbuffer。標(biāo)準(zhǔn)IO函數(shù)是帶緩存的Example34精選PPT打印兩次,因?yàn)椋瑯?biāo)準(zhǔn)I/O庫對普通輸出是全緩存的。35精選PPTbadPID.cintmain(void){pid_tchildpid;pid_tmypid;mypid=getpid();childpid=fork();if(childpid==-1){perror("Failedtofork");return1;}if(childpid==0)/*childcode*/printf("Iamchild%ld,ID=%ld\n",(long)getpid(),(long)mypid);else/*parentcode*/printf("Iamparent%ld,ID=%ld\n",(long)getpid(),(long)mypid);return0;}36精選PPTFilesharingAfterfork,Theparentandchildshareafiletableentryforeveryopendescriptor.Sotheparentandchildsharethesamefileoffset.Ifbothparentandchildwritetothesamedescriptor,withoutanyformofsynchronization,theiroutputwillbeintermixed.Therearetwonormalcasesforhandlingthedescriptorsafterafork.Theparentwaitsforthechildtocomplete.Theparentandchildeachgotheirownway.Thisscenarioisoftenthecasewithnetworkservers.37精選PPTSharingofopenfilesafterfork……fd0:fd1:fd2:fdflagsparentprocesstable……fd0:fd1:fd2:fdflagschildprocesstablefilestatusflagsfiletablescurrentfileoffsetv-nodeptrfilestatusflagscurrentfileoffsetv-nodeptrfilestatusflagscurrentfileoffsetv-nodeptrv-nodeinformationv-nodeInformationcurrentfilesizev-nodeinformationv-nodeInformationcurrentfilesizev-nodeinformationv-nodeInformationcurrentfilesizev-nodetables38精選PPTTwousesforforkWhenaprocesswantstoduplicateitselfsothattheparentandchildcaneachexecutedifferentsectionofcodeatsametime.Thisiscommonfornetworkserver.Whenaprocesswantstoexecuteadifferentprogram.Thisiscommonforshells.Inthiscasethechilddoesanexec

rightafteritreturnfromthefork.Someoperatingsystemscombinetheoperationsfork

andexectoonefunctionspawn.39精選PPTprocesschain.cintmain(intargc,char*argv[]){pid_tchildpid=0;inti,n;

if(argc!=2){/*checkforvalidnumberofcommand-linearguments*/fprintf(stderr,"Usage:%sprocesses\n",argv[0]);return1;}n=atoi(argv[1]);for(i=1;i<n;i++)

if(childpid=fork())

break;fprintf(stderr,"i:%dprocessID:%ldparentID:%ldchildID:%ld\n",i,(long)getpid(),(long)getppid(),(long)childpid);return0;}40精選PPTprocessfan.cintmain(intargc,char*argv[]){pid_tchildpid=0;inti,n;

if(argc!=2){/*checkforvalidnumberofcommand-linearguments*/fprintf(stderr,"Usage:%sprocesses\n",argv[0]);return1;}n=atoi(argv[1]);for(i=1;i<n;i++)if((childpid=fork())<=0)break;fprintf(stderr,"i:%dprocessID:%ldparentID:%ldchildID:%ld\n",i,(long)getpid(),(long)getppid(),(long)childpid);return0;}41精選PPTexitFunctionTherearethreewayforprocesstoterminatenormallyandtwoformsofabnormaltermination.Executingareturnfromthemain.Callingtheexitfunction.Callingthe_exitfunction.Callingtheabort,whichgenerateSIGABRTsignal.Whentheprocessreceivecertainsignal,whichmaybecausetheprocessterminate.Regardlesshowaprocessterminates,thesamecodeinthekerneliseventuallyexecuted.Thiskernelcodesclosesalltheopendescriptors,releasesthememory.42精選PPTexitFunction(Cont.)Wheneveraprocessterminate,thekernelgoesthroughallactiveprocessestoseeiftheterminatingprocessistheparentofanyprocessthatstillexists.Ifso,theparentprocessIDofthestillexistingprocessischangedtobe1(init).(Theparentterminatebeforechilddoes)Anothercase:Thekernelhastokeepacertainmountofinformationforeveryterminating,sothattheinformationisavailablewhenitsparentcallswaitorwaitpid.Minimally,thisinformationconsistsoftheprocessID,theterminationstatus,andtheamountofCPUtime,etc..(thechildterminatebeforeitsparent)43精選PPTdo_exit()將task_struct中的標(biāo)志成員設(shè)置為PF_EXITING;如果進(jìn)程記帳功能開啟,則調(diào)用acct_process輸出記帳調(diào)用__exit_mm()函數(shù)釋放進(jìn)程占用的mm_struct,如果沒有其他進(jìn)程使用它們,則徹底釋放;調(diào)用sem_exit()函數(shù)。如果進(jìn)程排隊(duì)等候IPC信號,則離開隊(duì)列;調(diào)用__exit_files()、__exit_fs()、__exit_namespace()和__exit_sighand(),以分別遞減文件描述符、文件系統(tǒng)數(shù)據(jù)、名字空間和信號處理函數(shù)的引用計(jì)數(shù);設(shè)置task_struct的成員exit_code為exit()函數(shù)提供的參數(shù);調(diào)用exit_notify()向符進(jìn)程發(fā)送信號,并將其子進(jìn)程的父進(jìn)程重新設(shè)置為線程組中的其他線程或init進(jìn)程,并把進(jìn)程狀態(tài)設(shè)置為TASK_ZOMBIE;最后,調(diào)用schedule()切換到其他進(jìn)程;44精選PPTwait

andwaitpidFunctionWhenaprocessterminates,eithernormallyorabnormally,theparentisnotifiedbythekernelsendingtheSIGCHLDsignal.

pid_twait(int*statloc);pid_twaitpid(pid_tpid,int*statloc,intoptions);Whenaprocesscallswaitorwaitpid,itwill:block(ifallofitschildrenarestillrunning)orReturnimmediatelywiththeterminationstatusofachild(ifachildhasreturnedandiswaiting)orReturnimmediatelywithanerror.(Ifitdoesn’thaveanychild)IftheprocessiscallingwaitafterreceivingtheSIGCHLD,weexpectwaittoreturnimmediately.

一個(gè)進(jìn)程需要等待其所有子進(jìn)程終止?問題:45精選PPT刪除進(jìn)程描述符Wait這函數(shù)族都是調(diào)用一個(gè)系統(tǒng)調(diào)用wait4(),它的標(biāo)準(zhǔn)動作是掛起調(diào)用進(jìn)程,直到其中某個(gè)子進(jìn)程退出,然后調(diào)用relase_task():調(diào)用free_uid()減少該進(jìn)程擁有者的進(jìn)程使用計(jì)數(shù);調(diào)用unhash_process()從pidhash上刪除該進(jìn)程,同時(shí)也要從task_list中刪除該進(jìn)程;調(diào)用put_task_struct釋放進(jìn)程內(nèi)核棧和thread_info結(jié)構(gòu)所占的頁,并釋放task_struct所占的高速緩存46精選PPTfanwait.cintmain(intargc,char*argv[]){pid_tchildpid;inti,n;if(argc!=2){fprintf(stderr,"Usage:%sn\n",argv[0]);return1;}n=atoi(argv[1]);for(i=1;i<n;i++)if((childpid=fork())<=0)break;

while(wait(NULL)>0);/*waitforallofyourchildren*/fprintf(stderr,"i:%dprocessID:%ldparentID:%ldchildID:%ld\n",i,(long)getpid(),(long)getppid(),(long)childpid);return0;}47精選PPTparentwait.cintmain(void){pid_tchildpid;/*setupsignalhandlershere...*/childpid=fork();if(childpid==-1){perror("Failedtofork");return1;}if(childpid==0)fprintf(stderr,"Iamchild%ld\n",(long)getpid());elseif(wait(NULL)!=childpid)fprintf(stderr,"Asignalmusthaveinterruptedthewait!\n");elsefprintf(stderr,"Iamparent%ldwithchild%ld\n",(long)getpid(),(long)childpid);return0;}48精選PPTchainwaitmsg.cintmain(intargc,char*argv[]){pid_tchildpid;inti,n;pid_twaitreturn;

if(argc!=2){/*checknumberofcommand-linearguments*/fprintf(stderr,"Usage:%sprocesses\n",argv[0]);return1;}n=atoi(argv[1]);for(i=1;i<n;i++)if(childpid=fork())break;

while(childpid!=(waitreturn=wait(NULL)))if((waitreturn==-1)&&(errno!=EINTR))break;fprintf(stderr,"Iamprocess%ld,myparentis%ld\n",(long)getpid(),(long)getppid());return0;}49精選PPTwaitandwaitpidFunction(Cont.)Therearethreemutuallymacrosthattellushowtheprocessterminate.Theycandeterminewhetherthechildprocesswasnormalexitorabnormalreturn.Ifchildprocesswasabnormalreturn,wecanalsogetthesignalnumber.50精選PPTwaitandwaitpidFunction(Cont.)51精選PPTShowreturn.cvoidshow_return_status(void){pid_tchildpid;intstatus;childpid=r_wait(&status);if(childpid==-1)perror("Failedtowaitforchild");elseif(WIFEXITED(status)&&!WEXITSTATUS(status))printf("Child%ldterminatednormally\n",(long)childpid);elseif(WIFEXITED(status))printf("Child%ldterminatedwithreturnstatus%d\n",(long)childpid,WEXITSTATUS(status));elseif(WIFSIGNALED(status))printf("Child%ldterminatedduetouncaughtsignal%d\n",(long)childpid,WTERMSIG(status));elseif(WIFSTOPPED(status))printf("Child%ldstoppedduetosignal%d\n",(long)childpid,WSTOPSIG(status));}52精選PPTshowreturnmain.cvoidshow_return_status();intmain(void){intchildpid;childpid=fork();if(childpid==-1){perror("Couldnotfork");return1;}if(childpid>0)

show_return_status();else{fprintf(stderr,"Childprocess%ldabouttosleep\n",(long)getpid());sleep(5);fprintf(stderr,"Childprocess%ldabouttoexit\n",(long)getpid());}return0;}53精選PPTwaitandwaitpidFunction(Cont.)pid_twaitpid(pid_tpid,int*statloc,intoptions);Theinterpretationofthepidargumentforwaitpiddependsonitsvalue.pid==-1:waitsforanychildprocess.pid>0:waitsforthechildwhoseprocessIDequalpidpid==0:waitsforanychildwhoseprocessgroupIDequalsthatofthecallingprocesspid<-1:waitsforanychildwhoseprocessgroupIDequalstheabsolutevalueofpid.54精選PPTwaitandwaitpidFunction(Cont.)Theoptionsargumentletsusfurthercontroltheoperationofwaitpid.Thisargumentiseither0orfollowingvalue.WNOHANG:waitpidwillnotblockifachildspecifiedbypidisnotimmediatelyavailable.Inthiscase,thereturnvalueis0.WUNTRACED:Iftheimplementationsupportsjobcontrol,thestatusofanychildspecifiedbypidthathasstopped,andwhosestatushasnotbeenreportedsinceithasstoped,isreturned.55精選PPTwaitandwaitpidFunction(Cont.)Thedifferencesbetweenwaitandwaitpidfunctionsare:waitcanblockthecalleruntilachildprocessterminates,whilewaitpidhasanoptionthatpreventsitfromblocking.waitpiddoesn’twaitforthefirstchildtoterminate.Ithasanumberofoptionsthatcontrolwhichprocessitwaitfor.So,waitpidprovidesthreefeaturesthataren’tprovidedbythewaitfunction.waitpidletsuswaitforone(orgroup)particularprocess.waitpidprovidesanonblockingversionofwait.waitpidsupportsjobcontrol.56精選PPTwait3

andwait4Functions

#include<sys/resource.h>

pid_twait3(int*status,intoptions,structrusage*rusage)pid_twait4(pid_tpid,int*status,intoptions,structrusage*rusage)

Bothreturn:processIDifOK,0,or-1onerror.Thesetwofunctionsallowsthekerneltoreturnasummaryofresourceusedbytheterminatedprocessandallitschildprocesses.TheresourceinfoincludessuchastheamountofuserCPUtime,theamountofsystemCPUtime,andthelike.

structtimevalru_utime;/*usertimeused*/structtimevalru_stime;/*systemtimeused*/longru_msgsnd;/*messagessent*/longru_msgrcv;/*messagesreceived*/longru_nsignals;/*signalsreceived*/57精選PPTexecFunctionsTheforkfunctioncreatesacopyofthecallingprocess,butmanyapplicationsrequirethechildprocesstoexecutecodethatisdifferentfromthatoftheparent.Theexecfamilyoffunctionsprovidesafacilityforoverlayingtheprocessimageofthecallingprocesswithanewimage.

intexecl(constchar*pathname,constchar*arg0,……);intexecv(constchar*pathname,char*constargv[]);intexecle(constchar*pathname,constchar*arg0,……,char*constenvp[]);intexecve(constchar*pathname,char*constargv[],char*constenvp[]);intexeclp(constchar*filename,constchar*arg0,……);intexecvp(constchar*filename,char*constargv[]);What’sdifferen

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論