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

上传人:创****公 文档编号:1704792 上传时间:2019-10-23 格式:PPT 页数:137 大小:1.63MB
返回 下载 相关 举报
Ch4 Linux系统程序设计 进程控制和进程间通信.ppt_第1页
第1页 / 共137页
Ch4 Linux系统程序设计 进程控制和进程间通信.ppt_第2页
第2页 / 共137页
点击查看更多>>
资源描述

《Ch4 Linux系统程序设计 进程控制和进程间通信.ppt》由会员分享,可在线阅读,更多相关《Ch4 Linux系统程序设计 进程控制和进程间通信.ppt(137页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、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 queueDaemon

2、Thread,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_s

3、tructSystem 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” fun

4、ctionCall “_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 te

5、rminate 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 da

6、taHeapStack,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,

7、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(co

8、nst 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.#inc

9、lude 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

10、 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, w

11、orld!n”);fork();printf(“byen”);,The usage of “fork”,Code exampleif ( (pid=fork() 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

12、 = 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

13、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

14、/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

15、*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 时关闭 */,Us

16、ing 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);,Ex

17、ample: 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, couldnt execute: %s, buf);

18、 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 g

19、roup(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 signal

20、s,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一些硬件异常信

21、号执行系统默认动作捕捉信号,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 specif

22、ied 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(cant catch SIGUSR1); if (signal(SIGUSR2, sig_usr) = SIG_ERR) err_sys(cant catch SIGUSR2); for ( ; ; ) pause();,Send a signal,kill(2)

23、: 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

24、 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

25、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 timeR

26、ace 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

27、 *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 sigp

28、rocmask(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);(Returne

29、d 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; /* a

30、ddr 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,

31、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() file实现代码执行cmd1前if (fd1 != STDOUT_FILENO) if (dup2(fd1, STDO

32、UT_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

33、(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(pf

34、d0, ,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,管道和命名管道相同点不同点文件系

35、统中同步:一个重要的考虑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

36、 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

37、,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对象时指定关键字

38、(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.value0) asleep(s.queue); procedure v(var s:samephore) s.value=s.value+1; if (s.value=0) wakeup(s.q

39、ueue); ,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, .);,

展开阅读全文
相关资源
相关搜索

当前位置:首页 > pptx模板 > 校园应用

本站为文档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