欢迎来到得力文库 - 分享文档赚钱的网站! | 帮助中心 好文档才是您的得力助手!
得力文库 - 分享文档赚钱的网站
全部分类
  • 研究报告>
  • 管理文献>
  • 标准材料>
  • 技术资料>
  • 教育专区>
  • 应用文书>
  • 生活休闲>
  • 考试试题>
  • pptx模板>
  • 工商注册>
  • 期刊短文>
  • 图片设计>
  • ImageVerifierCode 换一换

    Ch4 Linux系统程序设计 进程控制和进程间通信.ppt

    • 资源ID:1704792       资源大小:1.63MB        全文页数:137页
    • 资源格式: PPT        下载积分:30金币
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录   QQ登录  
    二维码
    微信扫一扫登录
    下载资源需要30金币
    邮箱/手机:
    温馨提示:
    快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。
    如填写123,账号就是123,密码也是123。
    支付方式: 支付宝    微信支付   
    验证码:   换一换

     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    Ch4 Linux系统程序设计 进程控制和进程间通信.ppt

    Ch4 Linux System Programming Process & IPC,Jianjian SONGSoftware Institute, Nanjing UniversityOct, 2004,Content,Process & process environmentProcess ControlProcess identifier, fork, execProcess relationshipSignalInter-process communication (IPC)Pipe, FIFOsemaphore, shared memory, message queueDaemonThread,1. Process & Process Environment,What is a process?Program and processProcess: an address space with one or more threads executing within that address space, and the required system resources for those threads. (SUSv3),The startup of a process,System call “fork” Process resourcesstruct task_structSystem space stackSystem call “exec”The entry of C programs,System stack,The entry of C programs,crt0.occ/ldmain functionfunction prototype:int main(int argc, char *argv);,The termination of a process,Five ways of terminating a processNormal terminationReturn from “main” functionCall “exit” functionCall “_exit” functionAbnormal terminationCall “abort” functionTerminated by a signal,exit & _exit functions,Function prototype:#include void exit(int status);#include void _exit(int status);Exit statusDifference_exit is corresponding to a system call, while “exit” is a library function._exit terminate a process immediately.,Exit handler,atexit functionRegister a function to be called at normal program termination.Prototype:#include int atexit(void (*function)(void);on_exit functionExample,The memory map of a C program,Text segment (code segment)Data segmentInitialized dataUninitialized dataHeapStack,Command line arguments,main functionint main(int argc, char *argv);Example:The implementation of echo(1)Command line optionStandard usagegetopt function,getopt function,Prototype:int getopt(int argc, char *const argv, const char *optstring);extern char *optarg;extern int optind, opterr, optopt;Question:getopt(argc, argv, “if:lr”);Program example (P104, in BLP),Environment variables,Environment tableEnvironment pointerextern char *environ;,putenv & getenv functions,Get, set or unset an environment variable#include char *getenv(const char *name);int putenv(char *string);int setenv(const char *name, const char *value, int overwirte);void unsetenv(const char *name);,Shared object,Shared objectDynamic linkAdvantages and disadvantagesExampleHow to create a static and shared library?How to use (link) a static or shared library?,Memory allocation,Allocate and free dynamic memory.#include void *malloc(size_t size);void *calloc(size_t nmemb, size_t size);void free(void *ptr);void realloc(void *ptr, size_t size);,2. Process control,Process identifierSystem call “fork”The simple synchronization between parent and child processThe “exec” function familyExample: The implementation of a simple shell,Process identifier,fork,fork: create a child process#include #include pid_t fork(void);returned value: pid of child (in the current (parent) process), 0 (in child process), -1 (failure),A simple example,#include #include #include /* fork系统调用的第一个例子(不含错误检查)*/void main()printf(“Hello, world!n”);fork();printf(“byen”);,The usage of “fork”,Code exampleif ( (pid=fork() < 0) /* error handling */ else if (pid = 0) /* child */ else /* parent */;Program exampleProgram8-1 in APUE,File sharing,所有由父进程打开的描述符都被复制到子进程中。父、子进程每个相同的打开描述符共享一个文件表项,vfork & clone functions,vfork#include #include pid_t vfork(void);clone#include int clone(int (*fn)(void *), void *child_stack, int flag, void *arg);,The simple synchronization between parent and child process,The relationship between parent and child processwait and waitpid functions,The relationship between parent and child process,The parent terminates before the childOrphan processThe child terminates before the parentSIGCHLD signalHandled by wait/waitpid in parentNot handled by wait/wait in parent -> zombie,wait & waitpid functions,Wait for process terminationPrototype#include #include pid_t wait(int *status);pid_t waitpid(pid_t pid, int *status, int options);Example,Race condition,int main(void) pid_tpid; if ( (pid = fork() < 0) err_sys("fork error"); else if (pid = 0) charatatime("output cccccccccccc from childn"); else charatatime("output pppppppppp from parentn"); exit(0);,An improvement,int main(void) pid_tpid; TELL_WAIT(); if ( (pid = fork() < 0) err_sys("fork error"); else if (pid = 0) WAIT_PARENT();/* parent goes first */ charatatime("output cccccccccccc from childn"); else charatatime("output pppppppppp from parentn"); TELL_CHILD(pid); exit(0);,The “exec” family of functions,Replace the current process image with a new process image.执行新程序的进程保持原进程的一系列特征:pid, ppid, uid, gid, working directory, root directory euid/egid?打开文件描述符?,Functions prototypes,#include extern char *environ;int execl(const char *path, const char *arg, .);int execlp(const char *file, const char *arg, .);int execle(const char *path, const char *arg, ., char * const envp);int execv(const char *path, char * const argv);int execvp(const char *file, char * const argv);#include int execve(const char *filename, char * const argv, char * const envp);,exec and opened file descriptor,close-on-exec bit of a file descriptorSet by “fcntl” functionfcntl(fd, F_SETFD, 0); /*系统默认, 打开文件描述符在 exec 时不关闭 */fcntl(fd, F_SETFD, 1); /*打开文件描述符在 exec 时关闭 */,Using fork and exec together,Two ways of using forkThe parent process duplicates itself, and then two different pieces of codes are executed in parent process and child process.A process want to execute another program.Example:The implementation of “system” functionint system(const char*cmdstring);,Example: a simple shell,printf("% ");/* print prompt */while (fgets(buf, MAXLINE, stdin) != NULL) bufstrlen(buf) - 1 = 0; /* replace newline with null */ if ( (pid = fork() < 0 ) err_sys(“fork error”); else if ( pid = 0 ) /* child */ execlp(buf, buf, (char *) 0); fprintf(stderr, "couldn't execute: %s", buf); exit(127); if ( (pid = waitpid(pid, ,3. Process relationship,父进程和子进程进程树ps, pstree命令,Startup & login (1),Login on serial terminal,Startup & login (2),Network login,Process group & session,Process groupThe set of one or more process(es).getpgrp/setpgid functionsSessionThe set of one or more process group(s).setsid functionControlling terminalWhy are they introduced?Job control,Process group & session (contd),Process group & session (contd),4. Signal,The concept of signalsThe “signal” functionSend a signalkill, raiseThe “alarm” and “pause” functionsReliable signal mechanism,The concept of signals,SignalSoftware interruptMechanism for handling asynchronous eventsHaving a name (beginning with SIG)Defined as a positive integer (in )How to produce a signal按终端键,硬件异常,kill(2)函数,kill(1)命令,软件条件,.,Signals in Linux/UNIX,Signals in Linux/UNIX (contd),Signal handling,忽略信号不能忽略的信号:SIGKILL, SIGSTOP一些硬件异常信号执行系统默认动作捕捉信号,The “signal” function,Installs a new signal handler for the signal with number signum.#include typedef void (*sighandler_t)(int);sighandler_t signal(int signum, sighandler_t handler);(Returned Value: the previous handler if success, SIG_ERR if error)The “handler” parametera user specified function, orSIG_DEF, orSIG_IGN,The ”signal” function (contd),Program examplestatic void sig_usr(int);int main(void) if (signal(SIGUSR1, sig_usr) = SIG_ERR) err_sys("can't catch SIGUSR1"); if (signal(SIGUSR2, sig_usr) = SIG_ERR) err_sys("can't catch SIGUSR2"); for ( ; ; ) pause();,Send a signal,kill(2): send signal to a process#include #include int kill(pid_t pid, int sig);(Returned Value: 0 if success, -1 if failure)raise(3): send a signal to the current process#include int raise(int sig);(Returned Value: 0 if success, -1 if failure),alarm & pause functions,alarm: set an alarm clock for delivery of a signal#include unsigned int alarm(unsigned int seconds);(Returned value: 0, or the number of seconds remaining of previous alarm)pause: wait for a signal#include int pause(void);(Returned value: -1, errno is set to be EINTR),alarm & pause functions (contd),Program exampleThe implementation of the “sleep” functionunsigned int sleep1(unsigned int nsecs) if ( signal(SIGALRM, sig_alrm) = SIG_ERR) return(nsecs); alarm(nsecs); /* start the timer */ pause(); /*next caught signal wakes us up*/ return(alarm(0) ); /*turn off timer, return unslept time */,Possible problems,Problems related to timeRace conditionInterrupted system callsReentrancy,Reliable signal mechanism,Weakness of the signal functionSignal blocksignal maskSignal setsigset_t data typeSignal handling functions using signal setsigprocmask, sigaction, sigpending, sigsuspend,signal set operations,#include int sigemptyset(sigset_t *set);int sigfillset(sigset_t *set);int sigaddset(sigset_t *set, int signum);int sigdelset(sigset_t *set, int signum); (Return value: 0 if success, -1 if error)int sigismember(const sigset_t *set, int signum); (Return value: 1 if true, 0 if false),sigprocmask function,检测或更改(或两者)进程的信号掩码#include sigprocmask(int how, const sigset_t *set, sigset_t *oldset);(Return Value: 0 is success, -1 if failure)参数“how”决定对信号掩码的操作SIG_BLOCK: 将set中的信号添加到信号掩码(并集)SIG_UNBLOCK: 从信号掩码中去掉set中的信号(差集)SIG_SETMASK: 把信号掩码设置为set中的信号例外: SIGKILL, SIGSTOP,sigpending function,返回当前未决的信号集#include sigpending(sigset_t *set);(Returned Value: 0 is success, -1 if failure)Example: critical.c (Prog10-11 in APUE),sigaction function,检查或修改(或两者)与指定信号关联的处理动作#include sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);(Returned Value: 0 is success, -1 if failure)struct sigaction至少包含以下成员:handler_t sa_handler; /* addr of signal handler, or SIG_IGN, or SIG_DEL */sigset_t sa_mask;/* additional signals to block */int sa_flags;/* signal options */,sigsuspend function,用sigmask临时替换信号掩码,在捕捉一个信号或发生终止该进程的信号前,进程挂起。#include sigsuspend(const sigset *sigmask);(Returned value: -1, errno is set to be EINTR)sigsuspend和pause,signal function review,用sigaction实现signal函数Sigfunc * signal(int signo, handler_t func) struct sigactionact, oact;act.sa_handler = func;sigemptyset(,Example: solution of race condition,int main(void) pid_tpid; TELL_WAIT(); if ( (pid = fork() < 0) err_sys("fork error"); else if (pid = 0) WAIT_PARENT();/* parent goes first */ charatatime("output cccccccccccc from childn"); else charatatime("output pppppppppp from parentn"); TELL_CHILD(pid); exit(0);,static sigset_tnewmask, oldmask, zeromask;static void sig_usr(int signo) /* one handler for SIGUSR1, SIGUSR2 */sigflag = 1; return;void TELL_WAIT() if (signal(SIGUSR1, sig_usr) = SIG_ERR)err_sys("signal(SIGINT) error");if (signal(SIGUSR2, sig_usr) = SIG_ERR)err_sys("signal(SIGQUIT) error");sigemptyset(,void WAIT_PARENT(void) while (sigflag = 0)sigsuspend(/* tell child we're done */,5. Inter-process communication,IPC: Inter-Process CommunicationIPC mechanismsshared filesignalpipe, FIFO (named pipe), message queue, semaphore, shared memorysocket,IPC illustrations,Simple Client-Server or IPC model,The concept of pipe,PipePipe mechanism in a shelle.g. cmd1 | cmd2Pipe is half-duplex管道只能在共同祖先的进程间使用管道也是文件命名管道(FIFO),The pipe function,The pipe function: create a pipe#include int pipe(int filedes2);(Returned value: 0 if success, -1 if failure)A pipe: First In, First Outfiledes0:read, filedes1: write,A pipe in a single process,A pipe between the parent & child,The coordinationof pipe read & write,写管道时,常数PIPE_BUF规定了内核中管道缓存器的大小管道的一端关闭时,写端关闭,读该管道在所有数据都被读取后,read返回0,表示达到了文件结束读端关闭,写该管道产生信号SIGPIPE,Examples,pipe1.c,管道用于标准输入和标准输出,管道:shell中的形式cmd1 | cmd2重定向 cmd > file实现代码执行cmd1前if (fd1 != STDOUT_FILENO) if (dup2(fd1, STDOUT_FILENO) != STDOUT_FILENO) err_sys(“dup2 error to stdout); 执行cmd2前if (fd0 != STDIN_FILENO) if (dup2(fd0, STDIN_FILENO) != STDIN_FILENO) err_sys(“dup2 error to stdin);,Examples,pipe2.c,pipe Application(1):solution of race condition,int main(void) pid_tpid; TELL_WAIT(); if ( (pid = fork() < 0) err_sys("fork error"); else if (pid = 0) WAIT_PARENT();/* parent goes first */ charatatime("output cccccccccccc from childn"); else charatatime("output pppppppppp from parentn"); TELL_CHILD(pid); exit(0);,static intpfd2;void TELL_WAIT() if (pipe(pfd) < 0)err_sys("pipe error");void WAIT_PARENT(void) charc;if (read(pfd0, ,pipe Application(2): shell,shpipe.c,popen & pclose functions,popen, pclose: process I/O#include FILE *popen(const char *command, const char *type);int pclose(FILE *stream);,按页输出在程序中获得另一个程序的输出,Applications of popen & pclose,Home work: popen的实现,用pipe, fork实现popen,FIFO: named pipe,管道和命名管道相同点不同点文件系统中同步:一个重要的考虑mkfifo(1), mkfifo(3), mknod(1), mknod(2),创建FIFO,mkfifo: make a FIFO special file (a named pipe)#include #include int mkfifo(const char *pathname, mode_t mode);(Returned value: 0 if success, -1 if failure)Examplesfifo1.c (Ch12 in BLP)list a fifo (ls lF),用open打开一个FIFO,Review: “open” system callint open(const char *pathname, int flags);“flags” parameter必须指定的互斥模式:O_RDONLY, O_WRONLY, O_RDWRO_NONBLOCKconsideration:读端/写端同步,FIFO的同步和读写,打开FIFO时的同步一般情况下(没有说明O_NONBLOCK),只读打开要阻塞到某个其它进程为写打开此FIFO;类似的,为写打开一个FIFO要阻塞到某个其它进程为读而打开它。如果指定了O_NONBLOCK,则只读打开立即返回;只写打开也立即返回,但如果没有进程已经为读而打开此FIFO,那么open将出错返回 -1,errno置为ENXIO。读写FIFO时的同步same as pipe,同步示例,shell中使用fifo的例子cat my_fifofifo2.c (Ch12 in BLP),FIFO的应用(1),用FIFO复制输出流例,FIFO的应用(2),C/S应用程序例:client.c, server.c,System V IPC,IPC objects信号量(semaphore set)消息队列(message queue)共享内存(shared memory)shell命令ipcs, ipcrm,System V IPC的共同特征,标识符与关键字引用IPC对象:标识符创建IPC对象时指定关键字(key_t key;)key的选择;预定义常数IPC_PRIVATE;ftok函数内核将关键字转换成标识符许可权结构和文件类比struct ipc_perm,SV IPC System Calls Overview,Semaphore,并发程序设计互斥和同步PV操作(原语),PV操作和信号量,procedure p(var s:samephore) s.value=s.value-1; if (s.value<0) asleep(s.queue); procedure v(var s:samephore) s.value=s.value+1; if (s.value<=0) wakeup(s.queue); ,Linux/UNIX的信号量机制,semaphore setstruct semid_ds struct ipc_perm sem_perm; struct sem *sem_base; /* ptr to first sem in set */ time_t sem_otime; /* last operation time */ time_t sem_ctime; /* last change time */ ushort sem_nsems; /* count of sems in set */,semaphore set system calls,#include #include #include int semget(key_t key, int nsems, int semflg);int semop(int semid, struct sembuf *sops, unsigned nsops);int semctl(int semid, int semnum, int cmd, .);,

    注意事项

    本文(Ch4 Linux系统程序设计 进程控制和进程间通信.ppt)为本站会员(创****公)主动上传,得力文库 - 分享文档赚钱的网站仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知得力文库 - 分享文档赚钱的网站(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    关于得利文库 - 版权申诉 - 用户使用规则 - 积分规则 - 联系我们

    本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

    工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

    © 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

    黑龙江省互联网违法和不良信息举报
    举报电话:0468-3380021 邮箱:hgswwxb@163.com  

    收起
    展开