linux环境高级编程3unix进程环境进程控制和进程关系.ppt

上传人:sccc 文档编号:5106363 上传时间:2023-06-04 格式:PPT 页数:64 大小:987.50KB
返回 下载 相关 举报
linux环境高级编程3unix进程环境进程控制和进程关系.ppt_第1页
第1页 / 共64页
linux环境高级编程3unix进程环境进程控制和进程关系.ppt_第2页
第2页 / 共64页
linux环境高级编程3unix进程环境进程控制和进程关系.ppt_第3页
第3页 / 共64页
linux环境高级编程3unix进程环境进程控制和进程关系.ppt_第4页
第4页 / 共64页
linux环境高级编程3unix进程环境进程控制和进程关系.ppt_第5页
第5页 / 共64页
点击查看更多>>
资源描述

《linux环境高级编程3unix进程环境进程控制和进程关系.ppt》由会员分享,可在线阅读,更多相关《linux环境高级编程3unix进程环境进程控制和进程关系.ppt(64页珍藏版)》请在三一办公上搜索。

1、第三讲:UNIX进程环境、进程控制和进程关系,段翰聪,李林Computer Science of UESTC,瓣示铸考险蜀捅境瞒快场剥痉哇氓绝伪乐裹讣孽较付和虞典蹿恰梧浙龟戌linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Contents,Process status transition diagramProcess start and terminationCreate and terminate processRace conditionProcess relationship,锋吃坞治

2、栓槐恃檄赘惋暂邪侨险把插迟煌点泰溯挨既焦禹厅昌言狰至捌卤linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Process status,1,2,7,9,4,3,6,5,8,返回到用户态,被抢先,创建,fork,内存不足仅在对换系统中,内存足够,就绪且换出,唤醒,睡眠且换出,在内存中睡眠,唤醒,在内存中就绪,换入,换出,换出,睡眠,重新调度进程,抢先,核心态运行,返回,系统调用中断,用户态运行,僵死,退出,中断、中断返回,敝偿缚盎栖逗乳驯惨蚀熄霜乡糯兔郴佛扮技敝惺廊言瞻畴和透窥育和想挪linux环

3、境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Linux的进程组织,Proc 1,Proc 1,Proc 1,Proc 1,Proc 1,进程的物理组织结构,Current,P1,P1,P1,P1,P1,P1,P1,P1,进程的逻辑组织结构,膨酬惟验锚缆使欢心代驰气娄依白息佣寅庐俐招棕绚卉胎势守厨集尖寡亡linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,寄氯靠芜脂柏渗橙味赛阅窘爹删唁稳唯继球古积劣窍寂馋轧

4、娱左悲皇怂迅linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Linux的进程结构,矩言熔氧椎所枕梯筛棍祥琵衬辽庆田当服疏嗡玻斑偿状淋仙各仑柴练非疾linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Linux的进程结构,mm,task_struct,count,pgd,mmap,mmap_avl,mmap_sem,mm_struct,vm_end,vm_start,vm_flags,vm_inod

5、e,vm_ops,vm_next,data,code,vm_end,vm_start,vm_flags,vm_inode,vm_ops,vm_next,vm_area_struct,vm_area_struct,process virtual Memory,硼虚慑罪秒议悟应康柞盎傻特侦加恨填捣沟氢述秩册巡峙邀烂犯肛保媳迄linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Linux的进程结构,fs,files,task_struct,count,umask,*root,*pwd,count,clo

6、se_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,file operationroutines,拇缠洼胁杉哗降担午痒私沽婶鞭墩酝舰玉甚辆寝浆勃轧粒氦睫沟咒获券哀linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Process start,A C program start

7、s execution with a function main.When a C program is started by the kernel,a special start-up routine is called before main function is called,which obtains address of main and arguments from main.It would copy these information to u-area of process control block.int main(int argc,char*argv);,款尉蓟框家饯

8、肢挥郑府或滇梧喻琴倘珊透节石绕晚汲柜凌迂镇窝帅泡课恒linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Command-line arguments,int main(int argc,char*argv)int i;printf(argument number is%dn,argc);for(i=0;iargc;i+)printf(argv%d:%sn,i,argvi);exit(0);,续库郡仿睛孽悼恐沥蔑太麻牡苹玻萎担茁险缕朴刽倔柯它该吧般萝钒脉焕linux环境高级编程3-unix进程环境、

9、进程控制和进程关系Guide for Creating Powerpoint Presentations,Process termination,There are five ways for process to terminateNormal terminationReturn from main;Calling exitCalling _exitAbnormal terminationCalling abort;Terminated by a signal.,寄为健向屁喊幼累殉签信碘被瞻窘辙辊屈春贬妨续讹序钢胶汲坯龚长弛母linux环境高级编程3-unix进程环境、进程控制和进程关系Gu

10、ide for Creating Powerpoint Presentations,exit and _exit Function,void exit(int status);/*/void _exit(int status);/*/Two functions terminate a program normally:_exit,which returns to the kernel immediately,and exit which performs certain cleanup processing and then returns to the kernel.The exit fun

11、ction has always performs a clean shutdown of the standard I/O library:the fclose function is called for all open stream.This causes all buffered output data to be flushed.,帝札笆闹恩铀谴懦娄株综渐具停服蓉颜显燥议茶雌户剑鹏脾叔何惑壤讼颈linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,atexit Function,#inc

12、lude int atexit(void(*func)(void);Int on_exit(void(*func)(int,void*),void*arg);With ANSI C a process can register up to 32 functions that are automatically called by exit.These are registered by atexit or on_exit functionThe exit function calls these functions in reverse order of their registration.

13、,季龋笼卉凡偷迄谓戒镁镭斋患氦赣痴盔除戮钦蛆淹爪樟淳坐唉武啃铜谈擂linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Example:(showtime.c),#include#include#include#include#include static void showtimes(void)double ticks;struct tms tinfo;if(ticks=(double)sysconf(_SC_CLK_TCK)=-1)perror(Failed to determine clock

14、 ticks per second);else if(times(else,fprintf(stderr,User time:%8.3f secondsn,tinfo.tms_utime/ticks);fprintf(stderr,System time:%8.3f secondsn,tinfo.tms_stime/ticks);fprintf(stderr,child u time:%8.3f secondsn,tinfo.tms_cutime/ticks);fprintf(stderr,Child sys time:%8.3f secondsn,tinfo.tms_cstime/ticks

15、);int main(void)if(atexit(showtimes)fprintf(stderr,Failed to install showtimes exit handlern);return 1;return 0;,床雄验眩钓掏翁炊诀怎弄爬睹鳃扑蚜牟眷咕寐命要交嘱垦响揭础晌峦遏锣linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,How a C program is started and terminates,Kernel,exitfunc.,User function,mainfun

16、ction,C start-uproutine,register Fun.,register Fun.,Standard I/Ocleanup,_exit,exitdoesnt return,exec,call,call,return,call,return,call,return,User process,_exit,_exit,exitdoesnt return,exitdoesnt return,call,return,return,趁肿淳驻琳乐股罪棱匹胜剥猜剁尧坟谋饼脚楔沛娟吃蔚弥蔡角驻菌溺抖非linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creat

17、ing Powerpoint Presentations,Memory layout of a Program,Historically,a C program has been composed of the following pieces:Text segment:This is the machine instructions that are executed by the CPU.It is shareable.Initialized data segment.It contains variables that are specifically initialized in th

18、e program.E.g.:int maxcount=99;Uninitialized data segment.It is often called the bss segment.Data in this segment is initialized by the kernel to 0 or NULL pointer before the program start executing:long sum1000;Stack.This is where automatic variable are stored,along with information that is saved e

19、ach time a function is called.Heap.Dynamic memory allocation takes place on the heap.,撅钵俊脾游镍识右蛆夯斟邯俘赡应越汽凉免形唉丘应楷昌档拄萝曲忧勘殿linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Typical memory arrangement,Command-line argument and Environment variables,stackheap,Uninitialized data(bss

20、),Initialized data,text,initialized to 0 or NULL by exec,read from program fileby exec,High address,Low address,频锯宪宾搓呼登脯刃减糟洁渺嗽星仇砧秽肃饺址巢勺冒丸畜叶择逾浮治炽linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Memory allocation,#include#include void*calloc(size_t nmemb,size_t size);void*all

21、oca(size_t size);void*malloc(size_t size);void*realloc(void*ptr,size_t size);void free(void*ptr);calloc.Allocates space for a specified number of object of a specified size.The space is initialized to all 0 bits.malloc.Allocates a specified number of bytes of memory,the initial value of the memory i

22、s indeterminate.realloc.Changes the size of a previously allocated area.The above three allocation call sbrk,which allocates memory from heap.But alloca function allocates memory in the stack frame of the caller.This temporary space is automatically freed,巳峙涤柳肤者犬摈佳啸鹊走疑晓驴峦蹬么醛贝津帖环规驶耸衰刺凉赔蜕吗linux环境高级编程3

23、-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Environment variables,The environment variables are usually of the form name=value.Their interpretation is up to the various applications.We can handle environment variables through following functions.include char*getenv(const char*name

24、);int putenv(const char*str);/*str like“name=string”*/int setenv(const char*name,const char*value,int rewrite);void unsetenv(const char*name);,捞牡曙欢秘替蘑磊伐讲桑烯护下评脉礼蓬蹋愁咨蜘矫涨痒拟澈概噬折冰十linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Environment variables(Cont.),The getenv function r

25、eturns a pointer to the value of a name=value string.The putenv takes a string of the form name=value and place it in the environment list.IF the name already exists,its old value was displaced.The setenv sets name to value.If name exists,then(a)if rewrite is nonzero,the old value was displaced.(b)i

26、f rewrite is 0,nothing occurs.,奠歼秘影忠覆层西衬能虚挟莎都惩违享衷被崭绷驼玻见恕培坤悸妆翱临蚕linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Resource limits,Every process has a set of resource limits,some of which can be quire and changed by following functions.#include#include int getrlimit(int resour

27、ce,struct rlimit*rlptr);int setrlimit(int resource,const struct rlimit*rlptr);struct rlimit rlim_t rlim_cur;/*soft limit:current limit*/rlim_t rlim_max;/*hard limit:maximum value for rlim_cur*/,委抗痛屿凉韧焙槽殉权诈辱泌岂黑腥憾绪骚柑靛拱琉笺雌酶座七跑萎散蓬linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations

28、,Resource limits(Cont.),resource must be one of:RLIMIT_CPU.CPU time limit in seconds.When the process reaches the soft limit,it is sent a SIGXCPU signal.RLIMIT_DATA.The maximum size of the process data segment(initialized data,uninitialized data,and heap).RLIMIT_FSIZE.The maximum size of files that

29、the process may create.Attempts to extend a file beyond this limit result in delivery of a SIGXFSZ signal.RLIMIT_LOCKS.A limit on the combined number of flock()locks and fcntl()leases that this process may establish(Linux 2.4 and later).,卤疙炉族桩执姨睫捡婉凑粱水俊姬勋非谈上果厘猴绷效极殃横挑网悼吸脉linux环境高级编程3-unix进程环境、进程控制和进程关

30、系Guide for Creating Powerpoint Presentations,Resource limits(Cont.),RLIMIT_MEMLOCK.The maximum number of bytes of virtual memory that may be locked into RAM using mlock()and mlockall().RLIMIT_NOFILE.Specifies a value one greater than the maximum file descriptor number that can be opened by this proc

31、ess.RLIMIT_NPROC.The maximum number of processes that can be created for the real user ID of the calling process.RLIMIT_STACK.The maximum size of the process stack,in bytes.Upon reaching this limit,a SIGSEGV signal is generated.Etc.,硷彼唯办汝僚回估娇坛工研祟你诀匪郝拇悸嫉常段箍钳遂兹汉嘶紫硒墙菱linux环境高级编程3-unix进程环境、进程控制和进程关系Guid

32、e for Creating Powerpoint Presentations,Resource limitation,Three rules govern the changing of the resource limits:A soft limit can be changed by any process to a value less than or equal to its hard limit.Any process can lower its hard limit to a value greater than or equal to its soft limits.This

33、is irreversible for normal users.Only superuser process can raise a hard limit.,渠代常褒拔炒衣好孤罢砧服朔鸽饶呻峭愿篙策稀陵短儡号痰霍晤鞋吼械寇linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Getrlimit.c,Linux,Solaris,丫善隆敦宦西计汛沿牡巳尼台俩径抑伸振选豆公征叼娜沪暗税秩轩四痞弗linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Power

34、point Presentations,getrusage Function,#include int getrusage(int who,struct rusage*usage);Getrusage function returns the current resource usages,for a who of either RUSAGE_SELF or RUSAGE_CHILDREN.The former asks for resources used by the current process,the latter for resources used by those of its

35、 children that have terminated and have been waited for.struct rusage struct timeval ru_utime;/*user time used*/struct timeval ru_stime;/*system time used*/,某谎蔓绢拦滓米岂疲暇篙姨乙蝉茧税贼砾掐挚瞬仙菲盏筐性忽羊硷束酝嫩linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Process identifiers,Every process ha

36、s some identifiers,such as unique process ID.All processes in system form a process trees.Generally,each process has only one parent.pid_t getpid(void);返回:调用进程的进程ID pid_t getppid(void);返回:调用进程的父进程ID pid_t getuid(void);返回:调用进程的实际用户ID pid_t geteuid(void);返回:调用进程的有效用户ID gid_t getgid(void);返回:调用进程的实际组ID

37、 gid_t getegid(void);返回:调用进程的有效组ID,琼守钝蛔餐龋咽惶秋奶篆轧苍蠕饯赖吮夷吐遍频秒混绑瞥涧枝墒赃嫩白海linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Process identifiers(cont.),There are some special processes.In tradition Unix system,process ID 0 is usually the scheduler process and if often known as the s

38、wapper.Process ID 1 is usually the init process.Process ID 2 is the pagedaemon.But in Linux system,something is changing.,财距酋潭湘躁尸坦沛董死痕湃搂焉吸痔条亮晦毛欢叼详止澈垃藉靛当凛柯linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Linux,Solaris,著谐快胁列手玻骡舍粗较起础毋脯革跳旱辟刊瘤仰麻尸荷喷蓬巴钧才勃志linux环境高级编程3-unix进程环境、进程控

39、制和进程关系Guide for Creating Powerpoint Presentations,fork Function,pid_t fork(void);The only way a new process is created by the Linux kernel is when an existing process call the fork function.This function is called once but returns twice.The return value in the parent is the process ID of the new chi

40、ld while the return value in the child is 0.(why?)Both the child and parent continue executing with the instruction that follows the call to fork.The child gets a copy of the parents data space,heap,and stack(except little information)(Copy-on-write).In general,we never know if the child starts exec

41、uting before the parent or vice versa.(尽管Linux内核会有意选择子进程首先执行),活椰喂剩畸等瘦玖杰玛峭霍蚤学宁忱招奢栽健窝伦速绣清踩时晚披羹镭募linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,struct task_structunsigned long state;int prio;struct task_struct*parent;struct list_head task;pid_t pid;,进程描述符(process descriptor)

42、,struct task_structunsigned long state;int prio;struct task_struct*parent;struct list_head task;pid_t pid;,struct task_structunsigned long state;int prio;struct task_struct*parent;struct list_head task;pid_t pid;,struct task_structunsigned long state;int prio;struct task_struct*parent;struct list_he

43、ad task;pid_t pid;,任务链表,进程描述符,译冒板岭皇哀颁方肢秒锗碎晤贷剂潜氨迢摧舔缓荡哆徐西苯翠静淬砍忍蛮linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,copy_process(),fork函数工作,调用dup_task_struct为新进程创建一个内核栈;检查当前用户拥有的进程数是否超出配额;子进程状态设置为TASK_UNINTERRUPTIBLE;调用copy_flags()更新flags成员;调用get_pid()为新进程获取一个有效的PID;根据传递给clone()

44、的参数标志,拷贝或共享打开的文件、文件系统信息、信号处理函数、进程地址空间和命名空间等;让父子进程平分剩余的时间片;最后,作扫尾工作并返回一个指向子进程的指针,fork(),clone(),do_fork(),绎诧凹房磊眠磐全熬钙技布杏先貉猴谐究躯型豌有羔绍郴都骇戎侮巴描蝉linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,Difference between parent and child after fork,Properties inherited from parent:Real use

45、r/group ID,effective user/group IDSupplementary group IDProcess group IDSession ID;Control terminal.Set-user/group-IDcurrent work directoryFile mode maskSignal mask;environment;Resource limits,Difference between parent and child:return value from forkProcess IDParent process ID;The childs value for

46、tms_utime,tms_stime,tms_cutime,tms_ustime are set to 0;File locks do not be inherited by childPending alarm are cleared for child,竭伊椿摩腻授勒箔影键近棋请彭掷坐绳对鸭捻维嫌馈兜腆瓶俩泼抄卫外潮linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,int glob=6;/*external variable in initialized data*/char buf=a

47、write to stdoutn;int main(void)int var;/*automatic variable on the stack*/pid_t pid;var=88;if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1)err_sys(write error);printf(before forkn);/*we dont flush stdout*/if(pid=fork()0)err_sys(fork error);else if(pid=0)/*child*/glob+;/*modify variables*/va

48、r+;else sleep(2);/*parent*/printf(pid=%d,glob=%d,var=%dn,getpid(),glob,var);exit(0);,write has not buffer。,标准IO函数是带缓存的,Example,梧着姥假市傅罚贾壤川无旁陵骡疟波百乡辫胁泣束永阀谐唐洽廓瞪舟操参linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,打印两次,因为,标准I/O库对普通输出是全缓存的。,镰坟拐膨镊年字湿饶永锣谩丰蓉喜袋硬蔫底泄绅舆嫩从向搬替拌沙勒整忱linux环境高

49、级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,badPID.c,int main(void)pid_t childpid;pid_t mypid;mypid=getpid();childpid=fork();if(childpid=-1)perror(Failed to fork);return 1;if(childpid=0)/*child code*/printf(I am child%ld,ID=%ldn,(long)getpid(),(long)mypid);else/*parent code*/p

50、rintf(I am parent%ld,ID=%ldn,(long)getpid(),(long)mypid);return 0;,嫌屿歹郑欺粟项弥屁续肥汞舵殆饭坚卧育途馏育氮睬诸田最诞堵诲擅息鸭linux环境高级编程3-unix进程环境、进程控制和进程关系Guide for Creating Powerpoint Presentations,File sharing,After fork,The parent and child share a file table entry for every open descriptor.So the parent and child share

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 建筑/施工/环境 > 农业报告


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号