




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領
文檔簡介
1、1操作系統(tǒng)進程4次課2Operating SystemsContemporary Applications never access hardware resources directlyThey rely on the services provided by the operating system3Abstractions Provided by OS4User and Kernel ModesProcesses are managed by a shared chunk of OS code called the kernelImportant: the kernel is not a
2、 separate process, but rather runs as part of some user processkernel virtual memory(code, data, heap, stack)memory mapped region forshared librariesrun-time heap(managed by malloc)user stack(created at runtime)unused0%espmemoryinvisible touser codebrk0 x08048000(32)read/write segment(.data, .bss)re
3、ad-only segment(.init, .text, .rodata)loaded from the executable file0 x00400000(64)5User and Kernel ModesThere is a mode bit in a control register Kernel (supervisor) mode if the bit is setUser mode if the bit is clearProcess running in kernel mode can execute any instructions in the instruction se
4、tcan access any memory locations in the systemProcess running in user mode canneither execute privileged instructionsnor directly reference code or data in the kernel area of the address spaceonly do above indirectly via os services6User and Kernel ModesA process running application code initially i
5、n user modechanges the user mode to kernel mode for some reasonschanges the kernel mode to user modeWhen control returns to the application codeHow can a process change from user mode to kernel mode ?The only way is via exception7ExceptionsAn exception is a transfer of control to the OS in response
6、to some event (i.e., change in processor state)User ProcessOSexceptionexception processingby exception handlerexception return (optional)event I currI nextInstruction related event: Page fault, arithmetic overflow Instruction unrelated event: Timer goes off A network package arrives8Exception Table1
7、. Each type of event has a unique exception number k2. Exception table entry k points to a function (exception handler).3. Handler k is called each time exception k occurs.Exceptiontable012.n-1code for exception handler 0code for exception handler 1code forexception handler 2code for exception handl
8、er n-1.Exception numbers9Exception HandlerException handlers run in kernel modemeans they have complete access to all system resourcesThe processor pushes a return address on the stack the return address is either the current instructionor the next instruction10Exception HandlerThe processor also pu
9、shes some additional processor state onto the stackwill be necessary to restart the interrupted program when the handler returnse.g. the current condition codesAll of these items are pushed onto the kernels stack 11Asynchronous exceptions (interrupts)Caused by events (changes in state) external to t
10、he processorIndicated by setting the processors interrupt pinhandler returns to “next” instruction.12Asynchronous exceptions (interrupts)Examples:I/O interruptshitting ctl-c at the keyboardarrival of a packet from a networkarrival of a data sector from a diskHard reset interrupthitting the reset but
11、tonSoft reset interrupthitting ctl-alt-delete on a PC13System context for exceptionsLocal/IO BusMemoryNetworkadapterSerial ATAcontrollerVideoadapterDisplayNetworkProcessorInterruptcontrollerIDEcontrollerUSB controllerKeyboardcontrollerKeyboardMousePrinterdiskCDROM14Synchronous exceptionsCaused by ev
12、ents that occur as a result of executing an instruction e.g. faulty instructionTrapsIntentional returns control to “next” instructionExamples: system calls, breakpoint traps15Synchronous exceptionsFaultsUnintentional but possibly recoverable either re-executes faulting (“current”) instruction or abo
13、rts.Examples: page faults (recoverable), protection faults (unrecoverable)AbortsUnintentional and unrecoverableaborts current programExamples: parity error, machine check16Synchronous exceptionsExceptions in IA32 systems17Fault Example #1Memory ReferenceUser writes to memory locationThat portion (pa
14、ge) of users memory is currently on diskint a1000;main () a500 = 13;80483b7: c7 05 10 9d 04 08 0d movl $0 xd,0 x8049d1018Fault Example #1User ProcessOSpage faultCreate page and load into memoryreturnevent movlint a1000;main () a500 = 13;80483b7: c7 05 10 9d 04 08 0d movl $0 xd,0 x8049d1019Fault Exam
15、ple #2Memory ReferenceUser writes to memory locationAddress is not validint a1000;main () a5000 = 13;80483b7: c7 05 60 e3 04 08 0d movl $0 xd,0 x804e36020Fault Example #2User ProcessOSpage faultDetect invalid addressevent movlSignal processint a1000;main () a5000 = 13;80483b7: c7 05 60 e3 04 08 0d m
16、ovl $0 xd,0 x804e36021Synchronous exceptionsTrapsintentional exception A result of executing an instruction.Examples: read a file (read), create process (fork)System CallsA procedure-like interface between user programs and operating systemsControlled access to kernel services22System CallsSystem ca
17、lls in IA32 systems23System Call Example# hello world1 int main()2 3 write(1, hello, worldn, 13);4 exit(0);5 24System Call Example1 .section .data2 string:3 .ascii hello, worldn4 string_end:5 .equ len, string_end - string6 .section .text7 .globl mainmain:25System Call ExampleFirst, call write(1, hel
18、lo, worldn, 13)9 movl $4, %eax Sdystem call number 410 movl $1, %ebx stdout has descriptor 111 movl $string, %ecx Hello world string12 movl $len, %edx String length13 int $0 x80 System call codeNext, call exit(0)14movl $1, %eax System call number 015 movl $0, %ebx Argument is 016 int $0 x80 System c
19、all code26Trap ExampleWriting a FileOS must find the file, write the string to itReturns integer whether it is succeeded User ProcessOStrapwrite filereturnintmovl27ExceptionsInterruptTrapFaultAbort28Implementing the Process AbstractionRequires close cooperation between boththe low-level hardware and
20、the operating system software29ContextThe kernel maintains a context for each processContext containsValue of PC, register file, status registers, users stack, kernels stackKernel data structuresProcess table, page table, file tableThe context is the state that the kernel needs to restart a preempte
21、d process30Context switchingThe scheduler (a chunk of kernel code) does scheduling as followingDecides whether to preempt the current process during the execution of a process Selects a previously preempted process (scheduled process) to restartPreempts the current processSaves the context of the cu
22、rrent processRestarts the scheduled processRestores the saved context of the scheduled processPasses the control to this newly restored process31Three states of a processRunningThe process is either executing on the CPUor is waiting to be executed and will eventually be scheduledStoppedThe execution
23、 of the process is suspended and will not be scheduledTerminatedThe process is stopped permanently. 32Three states of a processProcessor states transitionA running process can e stoppedA stopped process can e runningA process can e terminatedWhen does the context switch happen?As a result of an inte
24、rruptTimer interruptThe executing process es stopped or terminated33Process AProcess BUser codeKernel codeUser codeKernel codeUser codeTimeContext switchContext switchreadDisk interruptReturn from readContext switching34System Call Error HandlingUnix system-level functions encounter an errortypicall
25、y return 1set the global integer variable errno to indicate what went wrong35System Call Error Handling1 if (pid = fork() 0) fprintf(stderr, fork error: %sn, strerror(errno);3 exit(0);4 1 void unix_error(char *msg) /* unix-style error */2 fprintf(stderr, %s: %sn, msg, strerror(errno);4 exit(0);5 1 i
26、f (pid = fork() 0)2 unix_error(fork error);36System Call Error Handling1 pid_t Fork(void)2 3 pid_t pid;45 if (pid = fork() 0)6 unix_error(Fork error);7 return pid;8 37Using System Calls of the Processes38Obtaining Process IDsThe getpid and getppid routines return an integer value of type pid_tpid_tD
27、efined in types.h as an int on Linux systems#include #include pid_t getpid(void);pid_t getppid(void);returns: PID of either the caller or the parent39Exit FunctionThe exit function terminates the process with an exit status of status. #include void exit(int status);this function does not return40For
28、k FunctionA parent process creates a new running child process by calling the fork function#include #include pid_t fork(void);Returns: 0 to child, PID of child to parent, -1 on error41Fork FunctionThe newly created child process is almost, but not quite, identical to the parent. The parent and the n
29、ewly created child have different PIDs.42Fork FunctionThe child gets an identical (but separate) copy of the parents user-level virtual address spaceincluding the text, data, and bss segments, heap, and user stack. also gets identical copies of any of the parents open file descriptorsWhich means the
30、 child can read and write any files that were open in the parent when it called fork. 43Fork FunctionCalled onceIn the parent process Returns twice: In the parent processReturn the PID of the childIn the newly created child process.Return 044Fork FunctionThe return value provides an unambiguous way
31、whether the program is executing in the parent or the child.45Fork Function1 #include csapp.h23 int main()4 5 pid_t pid;6 int x = 1;78 pid = Fork();9 if (pid = 0) /* child */10 printf(child : x=%dn, +x);11 exit(0);12 1314 /* parent */15 printf(parent: x=%dn, -x);16 exit(0);17 46Fork FunctionCall onc
32、e, return twice. As mentioned beforeThis is fairly straightforward for programs that create a single child. Programs with multiple instances of fork can be confusing need to be reasoned about carefully47Fork FunctionConcurrent executionThe parent and the child are separate processes that run concurr
33、ently. The instructions in their logical control flows can be interleaved by the kernel in an arbitrary way. We can never make assumptions about the interleaving of the instructions in different processes.48Fork FunctionDuplicate but separate address spacesImmediately after the fork function returne
34、d in each process, the address space of each process is identical. Local variable x has a value of 1 in both the parent and the child when the fork function returns in line 8. 49Fork Function1 #include csapp.h23 int main()4 5 pid_t pid;6 int x = 1;78 pid = Fork();9 if (pid = 0) /* child */10 printf(
35、child : x=%dn, +x);11 exit(0);12 1314 /* parent */15 printf(parent: x=%dn, -x);16 exit(0);17 50Fork FunctionDuplicate but separate address spaces. The parent and the child are separate processesthey each have their own private address spaces. Any subsequent changes that a parent or child makes to x
36、private not reflected in the memory of the other process. 51Fork FunctionDuplicate but separate address spacesThe variable x has different values in the parent and child when they call their respective printf statements.Shared filesLike stdoutConmmunication between child and parent52Fork Function1 #
37、include csapp.h23 int main()4 5 Fork();6 printf(hello!n);7 exit(0);8 (a) Calls fork once. (b) Prints two output lines.hellohellofork53Fork Function1 #include csapp.h23 int main()4 5 Fork();6 Fork();7 printf(hello!n);8 exit(0);9 (c) Calls fork twice. (d) Prints four output lines.hellohellohellohellof
38、orkforkfork54Fork Function1 #include csapp.h23 int main()4 5 Fork();6 Fork();7 Fork();8 printf(hello!n);9 exit(0);10 (e) Calls fork three times. (f) Prints eight output lines.hellohellohellohelloforkforkhellohellohellohelloforkforkforkforkfork55ZombieZombieis a terminated process which is not remove
39、d from the system immediately after it terminatesconsumes system memory resourcescan be reaped by its parentWhen the parent reaps the terminated childthe kernel passes the childs exit status to the parentand then discards the terminated process, at which point it ceases to exist56ZombieIf the parent
40、 process terminates without reaping its zombie children, the init process will reap them. The init process has a PID of 1 and is created by the kernel during system initializationLong-running programs should always reap their zombie childrenshells, servers57Wait_pid Function#include #include pid_t w
41、aitpid(pid_t pid, int *status, int options);pid_t wait(int *status);Returns: PID of child if OK, 0 (if WNOHANG) or -1 on error58Wait_pid Functionpid 0The wait set is the singleton child process whose process ID is equal to pidpid = -1The wait set consists of all of the parents child processespid_t w
42、aitpid(pid_t pid, int *status, int options);59Wait_pid Functionoptions0WNOHANGWUNTRACEDWUNTRACED | WNOHANGpid_t waitpid(pid_t pid, int *status, int options);60Wait_pid FunctionWIFEXITED(status),WEXITSTATUS(status)WIFSIGNALED(status),WTERMSIG(status)WIFSTOPPED(status),WSTOPSIG(status)pid_t waitpid(pi
43、d_t pid, int *status, int options);61Wait_pid Function1 #include csapp.h2 #define N 234 int main()5 6 int status, i;7 pid_t pid;89 /* Parent creates N children */10 for (i = 0; i 0) 16 if (WIFEXITED(status)17 printf(child %d terminated normally with exit18 status=%dn, pid, WEXITSTATUS(status);19 els
44、e20 printf(child %d terminated abnormallyn, pid);21 2223 /* The only normal term. is if there no more chds. */24 if (errno != ECHILD)25 unix_error(waitpid error);2627 exit(0);2863Wait_pid Functionunix./waitpid1child 22966 terminated normally with exit status=100child 22967 terminated normally with e
45、xit status=10164Wait_pid Function1 #include csapp.h2 #define N 234 int main()5 6 int status, i;7 pid_t pidN+1, retpid;89 /* Parent creates N children */10 for (i = 0; i 0) 16 if (WIFEXITED(status)18 printf(child %d terminated normally with exit 19 status=%dn, retpid, WEXITSTATUS(status);20 else21 pr
46、intf(child %d terminated abnormallyn, retpid);22 2324 /* The only normal term. is if there are no more chds. */25 if (errno != ECHILD)26 unix_error(waitpid error);2728 exit(0);2966Putting Process to SleepSuspends a process for some period of time.Returns zero if the requested amount of time has elap
47、sedReturns the number of seconds still left to sleep otherwise.#include unsigned int sleep(unsigned int secs);Returns: seconds left to sleepint pause(void);Always returns -167Loading and RunningLoads and runs the executable object file filename with the argument list argvthe environment variable lis
48、t envp. returns to the calling program only if there is an errorsuch as not being able to find filename. The Execve is called once and never returns#include int execve(const char *filename, const char *argv, const char *envp);does not return if OK, returns -1 on error68Loading and Runningenvpenvpn-1
49、.envp0envp1NULLPWD=/usr/drohPRINTER=ironUSER=drohenvpargvargvargc-1.argv0argv1NULLls-lt/usr/includeargvint execve(const char *filename, const char *argv, const char *envp);69The user stack when a new program starts70Unix ShellAn interactive application-level program thatruns other program on behalf
50、of the userVariants: sh, csh, tcsh, ksh, bashPerforms a sequence of read/evaluate steps and terminateRead: reads a command line from the userEvaluate: parses the command line and runs programs on behalf of the user 71/* The main routine for a simple shell program */1 #include csapp.h2 #define MAXARG
51、S 12834 /* function prototypes */5 void eval(char*cmdline);6 int parseline(const char *cmdline, char *argv);7 int mand(char *argv);8729 int main()10 11 char cmdlineMAXLINE; /* command line */1213 while (1) 14 /* read */15 printf( );16 Fgets(cmdline, MAXLINE, stdin);17 if (feof(stdin)18 exit(0);1920
52、/* evaluate */21 eval(cmdline);22 23 731 /* eval - evaluate a command line */2 void eval(char *cmdline)3 4 char *argvMAXARGS; /* argv for execve() */5 char bufMAXLINE; /* holds modified cmd line */6 int bg; /* should the job run in bg or fg? */7 pid_t pid; /* process id */89 strcpy(buf, cmdline);10
53、bg = parseline(buf, argv);11 if (argv0 = NULL)12 return; /* ignore empty lines */1374Parsing command lineParse the space separated command-line argumentsBuilds the argv vectorwhich will eventually be passed to execveThe first argument is assumed to be either the name of a built-in shell command that
54、 is interpreted immediatelyor an executable object filethat will be loaded and run in the context of a new child process7514 if ( mand(argv) 15 if (pid = Fork() = 0) /* execute in child */16 if (execve(argv0, argv, environ) 0) 17 printf(%s: Command not found.n, argv0);18 exit(0);19 20 217614 if ( ma
55、nd(argv) 15 if (pid = Fork() = 0) /* execute in child */16 if (execve(argv0, argv, environ) 0) 17 printf(%s: Command not found.n, argv0);18 exit(0);19 20 2134 /* if 1st arg is a builtin command, run it and return true */35 int mand(char *argv)36 37 if (!strcmp(argv0, quit) /* quit command */38 exit(
56、0);39 if (!strcmp(argv0, &) /* ignore singleton & */40 return 1;41 return 0; /* not a builtin command */42 77Foreground and BackgroundIf the last argument is a “&” characterparseline returns 1indicating the program should be executed in the background (the shell returns to the top of the loop and wa
57、its for the next command)Otherwiseparseline returns 0indicating the program should be run in the foreground (the shell waits for it to complete) 7822 /* parent waits for foreground job to terminate */23 if (!bg) /* foreground */24 int status;25 if (waitpid(pid, &status, 0) 0)26 unix_error(waitfg: wa
58、itpid error);27 28 else /* background,no way to reap child process */29 printf(%d %s, pid, cmdline);30 31 return;32 14 if ( mand(argv) 15 if (pid = Fork() = 0) /* execute in child */16 if (execve(argv0, argv, environ) kill -9 15213sends signal 9 (SIGKILL) to process 15213. 81Hardware EventsSIGFPE si
59、gnal (number 8) If a process attempts to divide by zero, then the kernel sends it a SIGFPE signal SIGILL signal (number 4) If a process executes an illegal instruction, the kernel sends it a SIGILL signal. SIGSEGV signal (number 11) If a process makes an illegal memory reference, the kernel sends it
60、 a SIGSEGV signal. 82Software EventsSIGINT signal (number 2) While a process is running in the foregroundif you type a ctrl-cthen the kernel sends a SIGINT signal to the process SIGKILL signal (number 9) A process can forcibly terminate another processby sending it a SIGKILL signalSIGCHLD signal (nu
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 合同樣本 食品配送合同
- 能源產(chǎn)品銷售合同
- 公司提前解除勞動合同補償協(xié)議范本
- 簡單承包合同范文
- 14我要的是葫蘆(教學設計)-2024-2025學年語文二年級上冊統(tǒng)編版
- 4《少讓父母為我操心》第二課時(教學設計)-部編版道德與法治四年級上冊
- 6-1《芣苢》教學設計 2024-2025學年統(tǒng)編版高中語文必修上冊
- 審計設備合同范本
- 教師資格證小學《教育教學知識與能力》基礎試題
- Module 4 Unit 2 He doesnt like these trousers.(教學設計)-2024-2025學年外研版(一起)英語二年級上冊
- 咖啡與茶文化培訓1
- 非標設備合同范本
- 訂單采購模板
- 輸電線路組成(金具、絕緣)
- 瀝青混凝土拌合站吊裝計算書
- 安全生產(chǎn)規(guī)章制度和崗位操作規(guī)程的目錄清單及內(nèi)容(無倉儲經(jīng)營單位)
- 鋼材質(zhì)量保證承諾書模板(6篇)
- 神筆馬良課文原文
- 內(nèi)科學教學課件:泌尿系統(tǒng)疾病總論
- 網(wǎng)絡安全培訓-
- 唐詩與三晉知到章節(jié)答案智慧樹2023年山西師范大學
評論
0/150
提交評論