Exceptional Control FlowPart IIOct. 22, 2002Exceptional Control FlowPart IIOct. 22, 2002TopicsTopicsn Process Hierarchyn Shellsn Signalsn Nonlocal jumpsclass17.ppt15-213“The course that gives CMU its Zip!”– 2 –15-213, F’02ECF Exists at All Levels of a SystemECF Exists at All Levels of a SystemExceptionsExceptionsn Hardware and operating system kernelsoftwareConcurrent processesConcurrent processesn Hardware timer and kernel softwareSignalsSignalsn Kernel softwareNon-local jumpsNon-local jumpsn Application codePrevious LectureThis Lecture– 3 –15-213, F’02The World of MultitaskingThe World of MultitaskingSystem Runs Many Processes ConcurrentlySystem Runs Many Processes Concurrentlyn Process: executing programl State consists of memory image + register values + programcountern Continually switches from one process to anotherl Suspend process when it needs I/O resource or timer eventoccursl Resume process when I/O available or given scheduling priorityn Appears to user(s) as if all processes executingsimultaneouslyl Even though most systems can only execute one process at atimel Except possibly with lower performance than if running alone– 4 –15-213, F’02Programmer’s Model of MultitaskingProgrammer’s Model of MultitaskingBasic FunctionsBasic Functionsn fork() spawns new processl Called once, returns twicen exit() terminates own processl Called once, never returnsl Puts it into “zombie” statusn wait() and waitpid() wait for and reap terminatedchildrenn execl() and execve() run a new program in an existingprocessl Called once, (normally) never returnsProgramming ChallengeProgramming Challengen Understanding the nonstandard semantics of the functionsn Avoiding improper use of system resourcesl E.g. “Fork bombs” can disable a system.– 5 –15-213, F’02Unix Process HierarchyUnix Process HierarchyLogin shellChildChildChildGrandchildGrandchild[0]Daemone.g. httpdinit [1]– 6 –15-213, F’02Unix Startup: Step 1Unix Startup: Step 1init [1][0]Process 0: handcrafted kernel processChild process 1 execs /sbin/init1. Pushing reset button loads the PC with the address of a small bootstrap program.2. Bootstrap program loads the boot block (disk block 0).3. Boot block program loads kernel binary (e.g., /boot/vmlinux)4. Boot block program passes control to kernel.5. Kernel handcrafts the data structures for process 0.Process 0 forks child process 1– 7 –15-213, F’02Unix Startup: Step 2Unix Startup: Step 2init [1][0]gettyDaemonse.g. ftpd, httpd/etc/inittabinit forks and execsdaemons per/etc/inittab, and forksand execs a getty programfor the console– 8 –15-213, F’02Unix Startup: Step 3Unix Startup: Step 3init [1][0]The getty processexecs a loginprogramlogin– 9 –15-213, F’02Unix Startup: Step 4Unix Startup: Step 4init [1][0]login reads login and passwd.if OK, it execs a shell.if not OK, it execs another gettytcsh– 10 –15-213, F’02Shell ProgramsShell ProgramsA A shellshell is an application program that runs programs on is an application program that runs programs onbehalf of the user.behalf of the user.n sh – Original Unix Bourne Shelln csh Ð BSD Unix C Shell, tcsh Ð Enhanced C Shelln bash ÐBourne-Again Shellint main(){ char cmdline[MAXLINE]; while (1) {/* read */printf("> ");Fgets(cmdline, MAXLINE, stdin);if (feof(stdin)) exit(0);/* evaluate */eval(cmdline); }}Execution is a sequence ofExecution is a sequence ofread/evaluate stepsread/evaluate steps– 11 –15-213, F’02Simple Shell eval FunctionSimple Shell eval Functionvoid eval(char *cmdline){ char *argv[MAXARGS]; /* argv for execve() */ int bg; /* should the job run in bg or fg? */ pid_t pid; /* process id */ bg = parseline(cmdline, argv); if (!builtin_command(argv)) {if ((pid = Fork()) == 0) { /* child runs user job */ if (execve(argv[0], argv, environ) < 0) {printf("%s: Command not found.\n", argv[0]);exit(0); }}if (!bg) { /* parent waits for fg job to terminate */ int status; if (waitpid(pid, &status, 0) < 0)unix_error("waitfg: waitpid error");}else /* otherwise, donÕt wait for bg job */ printf("%d %s", pid, cmdline); }}– 12 –15-213, F’02Problem with Simple Shell ExampleProblem with Simple Shell ExampleShell correctly waits for and reaps foreground jobs.Shell correctly waits for and reaps foreground jobs.But what about background jobs?But what about background jobs?n Will become zombies when they terminate.n Will never be reaped because shell (typically) will notterminate.n Creates a memory leak that will eventually crash the kernelwhen it runs out of memory.Solution: Reaping background jobs requires aSolution: Reaping background jobs requires amechanism called a mechanism called a signalsignal..– 13 –15-213, F’02SignalsSignalsA A signalsignal is a small message that notifies a process that is a small message that notifies a process thatan event of some type has occurred in the system.an event of some type has occurred in the system.n Kernel abstraction for exceptions and interrupts.n Sent from the kernel (sometimes at the request of anotherprocess) to a process.n Different signals are identified by small integer ID’sn The only information in a signal is its ID and the fact that itarrived.Timer signalTimer signalTerminateTerminateSIGALRMSIGALRM1414Segmentation violationSegmentation violationTerminate & DumpTerminate & DumpSIGSEGVSIGSEGV111117179922IDIDChild stopped or terminatedChild stopped or terminatedIgnoreIgnoreSIGCHLDSIGCHLDKill program (cannot override or ignore)Kill program (cannot override or ignore)TerminateTerminateSIGKILLSIGKILLInterrupt from keyboard (Interrupt from keyboard (ctlctl-c-c))TerminateTerminateSIGINTSIGINTCorresponding EventCorresponding EventDefault ActionDefault ActionNameName– 14 –15-213, F’02Signal Concepts Signal Concepts Sending a signalSending a signaln Kernel sends (delivers) a signal to a destination process byupdating some state in the context of the destinationprocess.n Kernel sends a signal for one of the following reasons:l Kernel has detected a system event such as divide-by-zero(SIGFPE) or the termination of a child process (SIGCHLD)l Another process has invoked the kill system call to explicitlyrequest the kernel to send a signal to the destination process.– 15 –15-213, F’02Signal Concepts (cont)Signal Concepts (cont)Receiving a signalReceiving a signaln A destination process receives a signal when it is forced bythe kernel to
View Full Document