linux环境高级编程3-unix进程环境、进程控制和进程关系_第1页
linux环境高级编程3-unix进程环境、进程控制和进程关系_第2页
linux环境高级编程3-unix进程环境、进程控制和进程关系_第3页
linux环境高级编程3-unix进程环境、进程控制和进程关系_第4页
linux环境高级编程3-unix进程环境、进程控制和进程关系_第5页
已阅读5页,还剩59页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第三讲:UNIX进程环境、进程控制和进程关系,段翰聪,李林ComputerScienceofUESTC,Contents,ProcessstatustransitiondiagramProcessstartandterminationCreateandterminateprocessRaceconditionProcessrelationship,Processstatus,1,2,7,9,4,3,6,5,8,返回到用户态,被抢先,创建,fork,内存不足仅在对换系统中,内存足够,就绪且换出,唤醒,睡眠且换出,在内存中睡眠,唤醒,在内存中就绪,换入,换出,换出,睡眠,重新调度进程,抢先,核心态运行,返回,系统调用中断,用户态运行,僵死,退出,中断、中断返回,Linux的进程组织,Proc1,Proc1,Proc1,Proc1,Proc1,进程的物理组织结构,Current,P1,P1,P1,P1,P1,P1,P1,P1,进程的逻辑组织结构,Linux的进程结构,Linux的进程结构,mm,task_struct,count,pgd,mmap,mmap_avl,mmap_sem,mm_struct,vm_end,vm_start,vm_flags,vm_inode,vm_ops,vm_next,data,code,vm_end,vm_start,vm_flags,vm_inode,vm_ops,vm_next,vm_area_struct,vm_area_struct,processvirtualMemory,Linux的进程结构,fs,files,task_struct,count,umask,*root,*pwd,count,close_on_exec,open_fs,fd0,fd1,f_mode,f_pcs,f_flags,f_count,f_owner,fd255,f_inode,f_op,f_version,fs_struct,inode,inode,inode,files_struct,file,fileoperationroutines,Processstart,ACprogramstartsexecutionwithafunctionmain.WhenaCprogramisstartedbythekernel,aspecialstart-uproutineiscalledbeforemainfunctioniscalled,whichobtainsaddressofmainandargumentsfrommain.Imain(intargc,char*argv);,Command-linearguments,intmain(intargc,char*argv)inti;printf(argumentnumberis%dn,argc);for(i=0;iargc;i+)printf(argv%d:%sn,i,argvi);exit(0);,Processtermination,TherearefivewaysforprocesstoterminateNormalterminationReturnfrommain;CallingexitCalling_exitAbnormalterminationCallingabort;Terminatedbyasignal.,exitand_exitFunction,voidexit(intstatus);/*/void_exit(intstatus);/*/Twofunctionsterminateaprogramnormally:_exit,whichreturnstothekernelimmediately,andexitwhichperformscertaincleanupprocessingandthenreturnstothekernel.TheexitfunctionhasalwaysperformsacleanshutdownofthestandardI/Olibrary:thefclosefunctioniscalledforallopenstream.Thiscausesallbufferedoutputdatatobeflushed.,atexitFunction,#includeintatexit(void(*func)(void);Inton_exit(void(*func)(int,void*),void*arg);WithANSICaprocesscanregisterupto32functionsthatareautomaticallycalledbyexit.Theseareregisteredbyatexitoron_exitfunctionTheexitfunctioncallsthesefunctionsinreverseorderoftheirregistration.,Example:(showtime.c),#include#include#include#include#includestaticvoidshowtimes(void)doubleticks;structtmstinfo;if(ticks=(double)sysconf(_SC_CLK_TCK)=-1)perror(Failedtodetermineclocktickspersecond);elseif(times(else,fprintf(stderr,Usertime:%8.3fsecondsn,tinfo.tms_utime/ticks);fprintf(stderr,Systemtime:%8.3fsecondsn,tinfo.tms_stime/ticks);fprintf(stderr,childutime:%8.3fsecondsn,tinfo.tms_cutime/ticks);fprintf(stderr,Childsystime:%8.3fsecondsn,tinfo.tms_cstime/ticks);intmain(void)if(atexit(showtimes)fprintf(stderr,Failedtoinstallshowtimesexithandlern);return1;return0;,HowaCprogramisstartedandterminates,Kernel,exitfunc.,Userfunction,mainfunction,Cstart-uproutine,registerFun.,registerFun.,StandardI/Ocleanup,_exit,exitdoesntreturn,exec,call,call,return,call,return,call,return,Userprocess,_exit,_exit,exitdoesntreturn,exitdoesntreturn,call,return,return,MemorylayoutofaProgram,Historically,aCprogramhasbeencomposedofthefollowingpieces:Textsegment:ThisisthemachineinstructionsthatareexecutedbytheCPU.Itisshareable.Initializeddatasegment.Itcontainsvariablesthatarespecificallyinitializedintheprogram.E.g.:intmaxcount=99;Uninitializeddatasegment.Itisoftencalledthebsssegment.Datainthissegmentisinitializedbythekernelto0orNULLpointerbeforetheprogramstartexecuting:longsum1000;Stack.Thisiswhereautomaticvariablearestored,alongwithinformationthatissavedeachtimeafunctioniscalled.Heap.Dynamicmemoryallocationtakesplaceontheheap.,Typicalmemoryarrangement,Command-lineargumentandEnvironmentvariables,stackheap,Uninitializeddata(bss),Initializeddata,text,initializedto0orNULLbyexec,readfromprogramfilebyexec,Highaddress,Lowaddress,Memoryallocation,#include#includevoid*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.Butallocafunctionallocatesmemoryinthestackframeofthecaller.Thistemporaryspaceisautomaticallyfreed,Environmentvariables,Theenvironmentvariablesareusuallyoftheformname=value.Theirinterpretationisuptothevariousapplications.Wecanhandleenvironmentvariablesthroughfollowingfunctions.includechar*getenv(constchar*name);intputenv(constchar*str);/*strlike“name=string”*/intsetenv(constchar*name,constchar*value,intrewrite);voidunsetenv(constchar*name);,Environmentvariables(Cont.),Thegetenvfunctionreturnsapointertothevalueofaname=valuestring.Theputenvtakesastringoftheformname=valueandplaceitintheenvironmentlist.IFthenamealreadyexists,itsoldvaluewasdisplaced.Thesetenvsetsnametovalue.Ifnameexists,then(a)ifrewriteisnonzero,theoldvaluewasdisplaced.(b)ifrewriteis0,nothingoccurs.,Resourcelimits,Everyprocesshasasetofresourcelimits,someofwhichcanbequireandchangedbyfollowingfunctions.#include#includeintgetrlimit(intresource,structrlimit*rlptr);intsetrlimit(intresource,conststructrlimit*rlptr);structrlimitrlim_trlim_cur;/*softlimit:currentlimit*/rlim_trlim_max;/*hardlimit:maximumvalueforrlim_cur*/,Resourcelimits(Cont.),resourcemustbeoneof:RLIMIT_CPU.CPUtimelimitinseconds.Whentheprocessreachesthesoftlimit,itissentaSIGXCPUsignal.RLIMIT_DATA.Themaximumsizeoftheprocessdatasegment(initializeddata,uninitializeddata,andheap).RLIMIT_FSIZE.Themaximumsizeoffilesthattheprocessmaycreate.AttemptstoextendafilebeyondthislimitresultindeliveryofaSIGXFSZsignal.RLIMIT_LOCKS.Alimitonthecombinednumberofflock()locksandfcntl()leasesthatthisprocessmayestablish(Linux2.4andlater).,Resourcelimits(Cont.),RLIMIT_MEMLOCK.ThemaximumnumberofbytesofvirtualmemorythatmaybelockedintoRAMusingmlock()andmlockall().RLIMIT_NOFILE.Specifiesavalueonegreaterthanthemaximumfiledescriptornumberthatcanbeopenedbythisprocess.RLIMIT_NPROC.ThemaximumnumberofprocessesthatcanbecreatedfortherealuserIDofthecallingprocess.RLIMIT_STACK.Themaximumsizeoftheprocessstack,inbytes.Uponreachingthislimit,aSIGSEGVsignalisgenerated.Etc.,Resourcelimitation,Threerulesgovernthechangingoftheresourcelimits:Asoftlimitcanbechangedbyanyprocesstoavaluelessthanorequaltoitshardlimit.Anyprocesscanloweritshardlimittoavaluegreaterthanorequaltoitssoftlimits.Thisisirreversiblefornormalusers.Onlysuperuserprocesscanraiseahardlimit.,Getrlimit.c,Linux,Solaris,getrusageFunction,#includeintgetrusage(intwho,structrusage*usage);Getrusagefunctionreturnsthecurrentresourceusages,forawhoofeitherRUSAGE_SELForRUSAGE_CHILDREN.Theformerasksforresourcesusedbythecurrentprocess,thelatterforresourcesusedbythoseofitschildrenthathaveterminatedandhavebeenwaitedfor.structrusagestructtimevalru_utime;/*usertimeused*/structtimevalru_stime;/*systemtimeused*/,Processidentifiers,Everyprocesshassomeidentifiers,suchasuniqueprocessID.Allprocessesinsystemformaprocesstrees.Generally,eachprocesshasonlyoneparent.pid_tgetpid(void);返回:调用进程的进程IDpid_tgetppid(void);返回:调用进程的父进程IDpid_tgetuid(void);返回:调用进程的实际用户IDpid_tgeteuid(void);返回:调用进程的有效用户IDgid_tgetgid(void);返回:调用进程的实际组IDgid_tgetegid(void);返回:调用进程的有效组ID,Processidentifiers(cont.),Therearesomespecialprocesses.IntraditionUnixsystem,processID0isusuallytheschedulerprocessandifoftenknownastheswapper.ProcessID1isusuallytheinitprocess.ProcessID2isthepagedaemon.ButinLinuxsystem,somethingischanging.,Linux,Solaris,forkFunction,pid_tfork(void);TheonlywayanewprocessiscreatedbytheLinuxkerneliswhenanexistingprocesscalltheforkfunction.Thisfunctioniscalledoncebutreturnstwice.ThereturnvalueintheparentistheprocessIDofthenewchildwhilethereturnvalueinthechildis0.(why?)Boththechildandparentcontinueexecutingwiththeinstructionthatfollowsthecalltofork.Thechildgetsacopyoftheparentsdataspace,heap,andstack(exceptlittleinformation)(Copy-on-write).Ingeneral,weneverknowifthechildstartsexecutingbeforetheparentorviceversa.(尽管Linux内核会有意选择子进程首先执行),structtask_structunsignedlongstate;intprio;structtask_struct*parent;structlist_headtask;pid_tpid;,进程描述符(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;,任务链表,进程描述符,copy_process(),fork函数工作,调用dup_task_struct为新进程创建一个内核栈;检查当前用户拥有的进程数是否超出配额;子进程状态设置为TASK_UNINTERRUPTIBLE;调用copy_flags()更新flags成员;调用get_pid()为新进程获取一个有效的PID;根据传递给clone()的参数标志,拷贝或共享打开的文件、文件系统信息、信号处理函数、进程地址空间和命名空间等;让父子进程平分剩余的时间片;最后,作扫尾工作并返回一个指向子进程的指针,fork(),clone(),do_fork(),Differencebetweenparentandchildafterfork,Propertiesinheritedfromparent:Realuser/groupID,effectiveuser/groupIDSupplementarygroupIDProcessgroupIDSessionID;Controlterminal.Set-user/group-IDcurrentworkdirectoryFilemodemaskSignalmask;environment;Resourcelimits,Differencebetweenparentandchild:returnvaluefromforkProcessIDParentprocessID;Thechildsvaluefortms_utime,tms_stime,tms_cutime,tms_ustimearesetto0;FilelocksdonotbeinheritedbychildPendingalarmareclearedforchild,intglob=6;/*externalvariableininitializeddata*/charbuf=awritetostdoutn;intmain(void)intvar;/*automaticvariableonthestack*/pid_tpid;var=88;if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1)err_sys(writeerror);printf(beforeforkn);/*wedontflushstdout*/if(pid=fork()0)err_sys(forkerror);elseif(pid=0)/*child*/glob+;/*modifyvariables*/var+;elsesleep(2);/*parent*/printf(pid=%d,glob=%d,var=%dn,getpid(),glob,var);exit(0);,writehasnotbuffer。,标准IO函数是带缓存的,Example,打印两次,因为,标准I/O库对普通输出是全缓存的。,badPID.c,intmain(void)pid_tchildpid;pid_tmypid;mypid=getpid();childpid=fork();if(childpid=-1)perror(Failedtofork);return1;if(childpid=0)/*childcode*/printf(Iamchild%ld,ID=%ldn,(long)getpid(),(long)mypid);else/*parentcode*/printf(Iamparent%ld,ID=%ldn,(long)getpid(),(long)mypid);return0;,Filesharing,Afterfork,Theparentandchildshareafiletableentryforeveryopendescriptor.Sotheparentandchildsharethesamefileoffset.Ifbothparentandchildwritetothesamedescriptor,withoutanyformofsynchronization,theiroutputwillbeintermixed.Therearetwonormalcasesforhandlingthedescriptorsafterafork.Theparentwaitsforthechildtocomplete.Theparentandchildeachgotheirownway.Thisscenarioisoftenthecasewithnetworkservers.,Sharingofopenfilesafterfork,fd0:,fd1:,fd2:,fdflags,parentprocesstable,fd0:,fd1:,fd2:,fdflags,childprocesstable,filestatusflags,filetables,currentfileoffset,v-nodeptr,filestatusflags,currentfileoffset,v-nodeptr,filestatusflags,currentfileoffset,v-nodeptr,v-nodeinformation,v-nodeInformationcurrentfilesize,v-nodeinformation,v-nodeInformationcurrentfilesize,v-nodeinformation,v-nodeInformationcurrentfilesize,v-nodetables,Twousesforfork,Whenaprocesswantstoduplicateitselfsothattheparentandchildcaneachexecutedifferentsectionofcodeatsametime.Thisiscommonfornetworkserver.Whenaprocesswantstoexecuteadifferentprogram.Thisiscommonforshells.Inthiscasethechilddoesanexecrightafteritreturnfromthefork.Someoperatingsystemscombinetheoperationsforkandexectoonefunctionspawn.,processchain.c,intmain(intargc,char*argv)pid_tchildpid=0;inti,n;if(argc!=2)/*checkforvalidnumberofcommand-linearguments*/fprintf(stderr,Usage:%sprocessesn,argv0);return1;n=atoi(argv1);for(i=1;in;i+)if(childpid=fork()break;fprintf(stderr,i:%dprocessID:%ldparentID:%ldchildID:%ldn,i,(long)getpid(),(long)getppid(),(long)childpid);return0;,processfan.c,intmain(intargc,char*argv)pid_tchildpid=0;inti,n;if(argc!=2)/*checkforvalidnumberofcommand-linearguments*/fprintf(stderr,Usage:%sprocessesn,argv0);return1;n=atoi(argv1);for(i=1;in;i+)if(childpid=fork()0:waitsforthechildwhoseprocessIDequalpidpid=0:waitsforanychildwhoseprocessgroupIDequalsthatofthecallingprocesspid-1:waitsforanychildwhoseprocessgroupIDequalstheabsolutevalueofpid.,waitandwaitpidFunction(Cont.),Theoptionsargumentletsusfurthercontroltheoperationofwaitpid.Thisargumentiseither0orfollowingvalue.WNOHANG:waitpidwillnotblockifachildspecifiedbypidisnotimmediatelyavailable.Inthiscase,thereturnvalueis0.WUNTRACED:Iftheimplementationsupportsjobcontrol,thestatusofanychildspecifiedbypidthathasstopped,andwhosestatushasnotbeenreportedsinceithasstoped,isreturned.,waitandwaitpidFunction(Cont.),Thedifferencesbetweenwaitandwaitpidfunctionsare:waitcanblockthecalleruntilachildprocessterminates,whilewaitpidhasanoptionthatpreventsitfromblocking.waitpiddoesntwaitforthefirstchildtoterminate.Ithasanumberofoptionsthatcontrolwhichprocessitwaitfor.So,waitpidprovidesthreefeaturesthatarentprovidedbythewaitfunction.waitpidletsuswaitforone(orgroup)particularprocess.waitpidprovidesanonblockingversionofwait.waitpidsupportsjobcontrol.,wait3andwait4Functions,#includepid_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*/,execFunctions,Theforkfunctioncreatesacopyofthecallingprocess,butmanyapplicationsrequirethechildprocesstoexecutecodethatisdifferentfromthatoftheparent.Texecl(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);,Whatsdifference?,若filename中无/,则按搜索路径搜索程序,Relationshipofthesixexec,execvp,execlp,execl,execle,execv,execve(系统调用),buildargv,buildargv,TryeachPATHprefix,useenviron,buildargv,execFunctions

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论