2023年全國(guó)碩士研究生考試考研英語一試題真題(含答案詳解+作文范文)_第1頁
已閱讀1頁,還剩136頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

1、Ch4 Linux System Programming – Process & IPC,Jianjian SONGSoftware Institute, Nanjing UniversityOct, 2004,Content,Process & process environmentProcess ControlProcess identifier, fork, exec…Process re

2、lationshipSignalInter-process communication (IPC)Pipe, FIFOsemaphore, shared memory, message queueDaemonThread,1. Process & Process Environment,What is a process?Program and processProcess: an address space w

3、ith 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 sta

4、ck…System 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

5、a processNormal terminationReturn from “main” functionCall “exit” functionCall “_exit” functionAbnormal terminationCall “abort” functionTerminated by a signal,exit & _exit functions,Function prototype:#includ

6、e 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 f

7、unctionRegister 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 seg

8、mentInitialized dataUninitialized dataHeapStack,Command line arguments,main functionint main(int argc, char *argv[]);Example:The implementation of echo(1)Command line optionStandard usagegetopt function,getopt

9、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),Environme

10、nt 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 se

11、tenv(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 u

12、se (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

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

14、rk,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

15、/* fork系統(tǒng)調(diào)用的第一個(gè)例子(不含錯(cuò)誤檢查)*/void main(){printf(“Hello, world!\n”);fork();printf(“bye\n”);},The usage of “fork”,Code exampleif ( (pid=fork()) < 0) { /* error handling */} else if (pid == 0) { /* child

16、 */} else { /* parent */};Program exampleProgram8-1 in APUE,File sharing,所有由父進(jìn)程打開的描述符都被復(fù)制到子進(jìn)程中。父、子進(jìn)程每個(gè)相同的打開描述符共享一個(gè)文件表項(xiàng),vfork & clone functions,vfork#include #include pid_t vfork(void);clone#include int

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

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

19、ie,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_tpi

20、d; if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid == 0) { charatatime("output cccccccccccc from child\n"); } else { charatatime("output pp

21、pppppppp from parent\n"); } exit(0);},An improvement,int main(void){ pid_tpid; TELL_WAIT(); if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid == 0) {

22、 WAIT_PARENT();/* parent goes first */ charatatime("output cccccccccccc from child\n"); } else { charatatime("output pppppppppp from parent\n"); TELL_CHILD(pid);

23、} exit(0);},The “exec” family of functions,Replace the current process image with a new process image.執(zhí)行新程序的進(jìn)程保持原進(jìn)程的一系列特征:pid, ppid, uid, gid, working directory, root directory …euid/egid?打開文件描述符?,Functions prot

24、otypes,#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

25、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,clos

26、e-on-exec bit of a file descriptorSet by “fcntl” functionfcntl(fd, F_SETFD, 0); /*系統(tǒng)默認(rèn), 打開文件描述符在 exec 時(shí)不關(guān)閉 */fcntl(fd, F_SETFD, 1); /*打開文件描述符在 exec 時(shí)關(guān)閉 */,Using fork and exec together,,Two ways of using forkThe par

27、ent 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 syst

28、em(const char*cmdstring);,Example: a simple shell,printf("%% ");/* print prompt */while (fgets(buf, MAXLINE, stdin) != NULL) { buf[strlen(buf) - 1] = 0; /* replace newline with null */ if ( (pid

29、= 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);

30、} if ( (pid = waitpid(pid, &status, 0)) < 0 ) /* parent */ err_sys(“waitpid error”); printf("%% ");},3. Process relationship,父進(jìn)程和子進(jìn)程進(jìn)程樹ps, pstree命令,Startup & login (1),Login on ser

31、ial 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 function

32、Controlling terminalWhy are they introduced?Job control,Process group & session (cont’d),Process group & session (cont’d),4. Signal,The concept of signalsThe “signal” functionSend a signalkill, raiseThe “al

33、arm” 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

34、to produce a signal按終端鍵,硬件異常,kill(2)函數(shù),kill(1)命令,軟件條件,...,Signals in Linux/UNIX,Signals in Linux/UNIX (cont’d),Signal handling,忽略信號(hào)不能忽略的信號(hào):SIGKILL, SIGSTOP一些硬件異常信號(hào)執(zhí)行系統(tǒng)默認(rèn)動(dòng)作捕捉信號(hào),The “signal” function,Installs a new s

35、ignal 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)Th

36、e “handler” parametera user specified function, orSIG_DEF, orSIG_IGN,The ”signal” function (cont’d),Program examplestatic void sig_usr(int);int main(void){ if (signal(SIGUSR1, sig_usr) == SIG_ERR) err_

37、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 pro

38、cess#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 fai

39、lure),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: w

40、ait for a signal#include int pause(void);(Returned value: -1, errno is set to be EINTR),alarm & pause functions (cont’d),Program exampleThe implementation of the “sleep” functionunsigned int sleep1(unsigned int

41、 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, r

42、eturn unslept time */},Possible problems,Problems related to timeRace conditionInterrupted system callsReentrancy,Reliable signal mechanism,Weakness of the signal functionSignal blocksignal maskSignal setsigset_t

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

44、*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

45、 false),sigprocmask function,檢測(cè)或更改(或兩者)進(jìn)程的信號(hào)掩碼#include sigprocmask(int how, const sigset_t *set, sigset_t *oldset);(Return Value: 0 is success, -1 if failure)參數(shù)“how”決定對(duì)信號(hào)掩碼的操作SIG_BLOCK: 將set中的信號(hào)添加到信號(hào)掩碼(并集)SIG_U

46、NBLOCK: 從信號(hào)掩碼中去掉set中的信號(hào)(差集)SIG_SETMASK: 把信號(hào)掩碼設(shè)置為set中的信號(hào)例外: SIGKILL, SIGSTOP,sigpending function,返回當(dāng)前未決的信號(hào)集#include sigpending(sigset_t *set);(Returned Value: 0 is success, -1 if failure)Example: critical.c (P

47、rog10-11 in APUE),sigaction function,檢查或修改(或兩者)與指定信號(hào)關(guān)聯(lián)的處理動(dòng)作#include sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);(Returned Value: 0 is success, -1 if failure)struct sigaction至少包含以下

48、成員: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臨時(shí)替換信號(hào)掩碼,在捕捉一個(gè)信號(hào)或發(fā)生終止該進(jìn)程

49、的信號(hào)前,進(jìn)程掛起。#include sigsuspend(const sigset *sigmask);(Returned value: -1, errno is set to be EINTR)sigsuspend和pause,signal function review,用sigaction實(shí)現(xiàn)signal函數(shù)Sigfunc * signal(int signo, handler_t func) {struct

50、sigactionact, oact;act.sa_handler = func;sigemptyset(&act.sa_mask);act.sa_flags = 0;if (signo == SIGALRM) {#ifdefSA_INTERRUPTact.sa_flags |= SA_INTERRUPT;/* SunOS */#endif} else {#ifdefSA_RESTART

51、act.sa_flags |= SA_RESTART;/* SVR4, 44BSD */#endif}if (sigaction(signo, &act, &oact) < 0)return(SIG_ERR);return(oact.sa_handler);},Example: solution of race condition,int main(void){ pid_t

52、pid; TELL_WAIT(); if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid == 0) { WAIT_PARENT();/* parent goes first */ charatatime("output cccccccccccc fr

53、om child\n"); } else { charatatime("output pppppppppp from parent\n"); TELL_CHILD(pid); } exit(0);},static sigset_tnewmask, oldmask, zeromask;static void sig_usr(int signo) {

54、/* 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_sy

55、s("signal(SIGQUIT) error");sigemptyset(&zeromask);sigemptyset(&newmask);sigaddset(&newmask, SIGUSR1);sigaddset(&newmask, SIGUSR2);/* block SIGUSR1 and SIGUSR2, and save current signal

56、 mask */if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)err_sys("SIG_BLOCK error");},void WAIT_PARENT(void) {while (sigflag == 0)sigsuspend(&zeromask);/* and wait for parent */s

57、igflag = 0;/* reset signal mask to original value */if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)err_sys("SIG_SETMASK error");}void TELL_CHILD(pid_t pid) {kill(pid, SIGUSR1);/* tell ch

58、ild we're done */},5. Inter-process communication,IPC: Inter-Process CommunicationIPC mechanismsshared filesignalpipe, FIFO (named pipe), message queue, semaphore, shared memorysocket,IPC illustrations,Simple C

59、lient-Server or IPC model,The concept of pipe,PipePipe mechanism in a shelle.g. cmd1 | cmd2Pipe is half-duplex管道只能在共同祖先的進(jìn)程間使用管道也是文件命名管道(FIFO),The pipe function,The pipe function: create a pipe#include int pipe(in

60、t filedes[2]);(Returned value: 0 if success, -1 if failure)A pipe: First In, First Outfiledes[0]:read, filedes[1]: write,A pipe in a single process,A pipe between the parent & child,The coordinationof pipe read

61、 & write,寫管道時(shí),常數(shù)PIPE_BUF規(guī)定了內(nèi)核中管道緩存器的大小管道的一端關(guān)閉時(shí),寫端關(guān)閉,讀該管道在所有數(shù)據(jù)都被讀取后,read返回0,表示達(dá)到了文件結(jié)束讀端關(guān)閉,寫該管道產(chǎn)生信號(hào)SIGPIPE,Examples,pipe1.c,管道用于標(biāo)準(zhǔn)輸入和標(biāo)準(zhǔn)輸出,管道:shell中的形式cmd1 | cmd2重定向 cmd > file實(shí)現(xiàn)代碼執(zhí)行cmd1前if (fd[1] != STDOUT_F

62、ILENO) {if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO) err_sys(“dup2 error to stdout);} 執(zhí)行cmd2前if (fd[0] != STDIN_FILENO) {if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) err_sys(“dup2 error to

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

64、= 0) { WAIT_PARENT();/* parent goes first */ charatatime("output cccccccccccc from child\n"); } else { charatatime("output pppppppppp from parent\n"); TELL_CHILD(

65、pid); } exit(0);},static intpfd[2];void TELL_WAIT() {if (pipe(pfd) < 0)err_sys("pipe error");}void WAIT_PARENT(void) {charc;if (read(pfd[0], &c, 1) != 1)err_sys("read error

66、");if (c != 'p')err_quit("WAIT_PARENT: incorrect data");}void TELL_CHILD(pid_t pid) {if (write(pfd[1], "p", 1) != 1)err_sys("write error");},pipe Application(2): sh

67、ell,shpipe.c,popen & pclose functions,popen, pclose: process I/O#include FILE *popen(const char *command, const char *type);int pclose(FILE *stream);,按頁輸出在程序中獲得另一個(gè)程序的輸出,Applications of popen & pclose,Home wor

68、k: popen的實(shí)現(xiàn),用pipe, fork實(shí)現(xiàn)popen,FIFO: named pipe,管道和命名管道相同點(diǎn)不同點(diǎn)文件系統(tǒng)中同步:一個(gè)重要的考慮mkfifo(1), mkfifo(3), mknod(1), mknod(2),創(chuàng)建FIFO,mkfifo: make a FIFO special file (a named pipe)#include #include int mkfifo(const char *

69、pathname, mode_t mode);(Returned value: 0 if success, -1 if failure)Examplesfifo1.c (Ch12 in BLP)list a fifo (ls –lF),用open打開一個(gè)FIFO,Review: “open” system callint open(const char *pathname, int flags);“flags” para

70、meter必須指定的互斥模式:O_RDONLY, O_WRONLY, O_RDWRO_NONBLOCKconsideration:讀端/寫端同步,FIFO的同步和讀寫,打開FIFO時(shí)的同步一般情況下(沒有說明O_NONBLOCK),只讀打開要阻塞到某個(gè)其它進(jìn)程為寫打開此FIFO;類似的,為寫打開一個(gè)FIFO要阻塞到某個(gè)其它進(jìn)程為讀而打開它。如果指定了O_NONBLOCK,則只讀打開立即返回;只寫打開也立即返回,但如果沒

溫馨提示

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

評(píng)論

0/150

提交評(píng)論