Sogang University
Exceptional Control Flow: Exceptions and Processes
CSE4100: System Programming
Youngjae Kim (PhD)
Copyright By PowCoder代写 加微信 powcoder
https://sites.google.com/site/youkim/home
Distributed Computing and Operating Systems Laboratory (DISCOS)
https://discos.sogang.ac.kr
Office: R911, E-mail:
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
¢ Exceptional Control Flow ¢ Exceptions
¢ Processes
¢ Process Control
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Control Flow
¢ Processors do only one thing:
§ From startup to shutdown, a CPU simply reads and executes (interprets) a sequence of instructions, one at a time
§ This sequence is the CPU’s control flow (or flow of control) Physical control flow
instn
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Altering the Control Flow
¢ Up to now: two mechanisms for changing control flow: § Jumps and branches
§ Call and return
React to changes in program state
¢ Insufficient for a useful system:
Difficult to react to changes in system state
§ Data arrives from a disk or a network adapter § Instruction divides by zero
§ User hits Ctrl-C at the keyboard
§ System timer expires
¢ System needs mechanisms for “exceptional control flow” Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Exceptional Control Flow
¢ Exists at all levels of a computer system
¢ Low level mechanisms § 1. Exceptions
§ Change in control flow in response to a system event (i.e., change in system state)
§ Implemented using combination of hardware and OS software
¢ Higher level mechanisms § 2. Process context switch
§ Implemented by OS software and hardware timer § 3. Signals
§ Implemented by OS software
§ 4. Nonlocal jumps: setjmp() and longjmp()
§ Implemented by C runtime library Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
¢ Exceptional Control Flow ¢ Exceptions
¢ Processes
¢ Process Control
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Exceptions
¢ An exception is a transfer of control to the OS kernel in
response to some event (i.e., change in processor state) § Kernel is the memory-resident part of the OS
§ Examples of events: Divide by 0, arithmetic overflow, page fault, I/O request completes, typing Ctrl-C
Event I_current I_next
Kernel code
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
• Return to I_current • Return to I_next
Exception processing by exception handler
Sogang University
Exception Tables
Exception numbers
¢ Each type of event has a unique exception number k
¢ k = index into exception table
(a.k.a. interrupt vector)
¢ Handler k is called each time
exception k occurs
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
exception handler 0
exception handler 1
exception handler 2
exception handler n-1
Sogang University
Classes of Exceptions
¢ Interrupts, Traps, Faults, and Aborts
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Asynchronous Exceptions (Interrupts)
¢ Caused by events external to the processor § Indicated by setting the processor’s interrupt pin § Handler returns to “next” instruction
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Asynchronous Exceptions (Interrupts)
¢ Examples:
§ Timer interrupt
§ Every few ms, an external timer chip triggers an interrupt
§ Used by the kernel to take back control from user programs § I/O interrupt from external device
§ Hitting Ctrl-C at the keyboard
§ Arrival of a packet from a network § Arrival of data from a disk
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Synchronous Exceptions
¢ Caused by events that occur as a result of executing an instruction: § Traps
§ Intentional
§ Examples: system calls, breakpoint traps, special instructions § Returns control to “next” instruction
§ Unintentional but possibly recoverable
§ Examples: page faults (recoverable), protection faults (unrecoverable), floating point exceptions
§ Either re-executes faulting (“current”) instruction or aborts § Aborts
§ Unintentional and unrecoverable
§ Examples: illegal instruction, parity error, machine check § Aborts current program
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Synchronous Exceptions (Traps) Examples: System calls
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Synchronous Exceptions (Fault Handling) Examples: Page faults
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Synchronous Exceptions (Abort Handling)
Examples: Hardware errors such as parity errors that occur when DRAM or SRAM bits are corrupted.
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
System Calls
¢ Each x86-64 system call has a unique ID number
¢ Examples:
Number Name Description
0 read Read file
1 write Write file
2 open Open file
3 close Close file
4 stat Get info about file
57 fork Create process
59 execve Execute a program
60 _exit Terminate process
62 kill Send signal to process
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
System Call Example: Opening File
¢ User calls: open(filename, options)
¢ Calls__openfunction,whichinvokessystemcallinstructionsyscall
00000000000e5d70 <__open>:
e5dfa: c3
mov $0x2,%eax # open is syscall #2 syscall # Return value in %rax cmp $0xfffffffffffff001,%rax
b8 02 00 00 00
48 3d 01 f0 ff ff
syscall cmp
Exception Returns
Kernel code
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
¢ %rax contains syscall number ¢ Otherargumentsin%rdi,
%rsi, %rdx, %r10, %r8, %r9
¢ Returnvaluein%rax
¢ Negative value is an error corresponding to negative errno
Sogang University
Fault Example: Page Fault
¢ User writes to memory location
¢ That portion (page) of user’s memory
is currently on disk
80483b7: c7 05 10 9d 04 08 0d movl $0xd,0x8049d10
Kernel code
int a[1000];
a[500] = 13; }
Exception: page fault
Return and reexecute movl
Copy page from disk to memory
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Fault Example: Invalid Memory Reference
int a[1000];
a[5000] = 13;
80483b7: c7 05 60 e3 04 08 0d movl $0xd,0x804e360
User code Kernel code
Exception: page fault
¢ SendsSIGSEGVsignaltouserprocess
¢ User process exits with “segmentation fault”
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Detect invalid address
Signal process
Sogang University
¢ Exceptional Control Flow ¢ Exceptions
¢ Processes
¢ Process Control
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
¢ Definition: A process is an instance of a running program.
§ One of the most profound ideas in computer science § Not the same as “program” or “processor”
¢ Process provides each program with two key abstractions:
§ Logical control flow
§ Each program seems to have exclusive use of the CPU
§ Provided by kernel mechanism called context switching
§ Private address space
§ Each program seems to have exclusive use of main
§ Provided by kernel mechanism called virtual memory Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Stack Heap
CPU Registers
Sogang University
Multiprocessing: The Illusion …
Stack Heap
Stack Heap
Stack Heap
¢ Computer runs many processes simultaneously § Applications for one or more users
§ Web browsers, email clients, editors, … § Background tasks
§ Monitoring network & I/O devices Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Multiprocessing Example
¢ Running program “top” on Mac
§ System has 123 processes, 5 of which are active
§ Identified by Process ID (PID) Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Multiprocessing: The (Traditional) Reality
Stack Stack Heap Heap
Data Data Code Code
Saved Saved registers registers
Stack … Heap
Saved registers
¢ Single processor executes multiple processes concurrently
§ Process executions interleaved (multitasking)
§ Address spaces managed by virtual memory system
§ Register values for nonexecuting processes saved in memory
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Multiprocessing: The (Traditional) Reality
Stack Stack Heap Heap
Data Data Code Code
Saved Saved registers registers
Stack … Heap
Saved registers
¢ Save current registers in memory Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Multiprocessing: The (Traditional) Reality
Stack Stack Heap Heap
Data Data Code Code
Saved Saved registers registers
Stack … Heap
Saved registers
¢ Schedule next process for execution Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Multiprocessing: The (Traditional) Reality
Stack Stack Heap Heap
Data Data Code Code
Saved Saved registers registers
Stack … Heap
Saved registers
¢ Load saved registers and switch address space (context switch)
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Multiprocessing: The (Modern) Reality
Stack Stack Heap Heap
Data Data Code Code
Saved Saved registers registers
Stack … Heap
Saved registers
¢ Multicore processors
§ Multiple CPUs on single chip
§ Share main memory (and some of the caches)
§ Each can execute a separate process
§ Scheduling of processes onto cores done by kernel
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Concurrent Processes
¢ Each process is a logical control flow.
¢ Two processes run concurrently (are concurrent) if their flows overlap in time
¢ Otherwise, they are sequential
¢ Examples (running on single core): § Concurrent: A & B, A & C
§ Sequential: B & C
Process A Process B Process C
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
User View of Concurrent Processes
¢ Control flows for concurrent processes are physically disjoint in time
¢ However, we can think of concurrent processes as running in parallel with each other
Process A Process B Process C
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Context Switching
¢ Processes are managed by a shared chunk of memory-
resident OS code called the kernel
§ Important: the kernel is not a separate process, but rather runs as
part of some existing process.
¢ Control flow passes from one process to another via a
context switch Process A
kernel code
kernel code
context switch context switch
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
¢ Exceptional Control Flow ¢ Exceptions
¢ Processes
¢ Process Control
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
System Call Error Handling
¢ On error, Linux system-level functions typically return -1
and set global variable errno to indicate cause.
¢ Hard and fast rule:
§ You must check the return status of every system-level function § Only exception is the handful of functions that return void
¢ Example:
if ((pid = fork()) < 0) {
fprintf(stderr, "fork error: %s\n", strerror(errno));
exit(0); }
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Error-reporting functions
¢ Can simplify somewhat using an error-reporting function:
void unix_error(char *msg) /* Unix-style error */ {
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(0); }
if ((pid = fork()) < 0) unix_error("fork error");
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Error-handling Wrappers
¢ We simplify the code we present to you even further by using Stevens-style error-handling wrappers:
pid_t Fork(void)
pid_t pid;
if ((pid = fork()) < 0) unix_error("Fork error");
return pid; }
pid = Fork();
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Obtaining Process IDs
¢ pid_t getpid(void) § Returns PID of current process
¢ pid_t getppid(void) § Returns PID of parent process
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Creating and Terminating Processes
From a programmer’s perspective, we can think of a process as being in one of three states
§ Process is either executing, or waiting to be executed and will
eventually be scheduled (i.e., chosen to execute) by the kernel ¢ Stopped
§ Process execution is suspended and will not be scheduled until further notice (next lecture when we study signals)
¢ Terminated
§ Process is stopped permanently
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Terminating Processes
¢ Process becomes terminated for one of three reasons:
§ Receiving a signal whose default action is to terminate (next lecture)
§ Returning from the main routine
§ Calling the exit function
¢ void exit(int status)
§ Terminates with an exit status of status
§ Convention: normal return status is 0, nonzero on error
§ Another way to explicitly set the exit status is to return an integer
value from the main routine
¢ exit is called once but never returns. Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Creating Processes
¢ Parent process creates a new running child process by
calling fork
¢ int fork(void)
§ Returns 0 to the child process, child’s PID to parent process § Child is almost identical to parent:
§ Child get an identical (but separate) copy of the parent’s virtual address space.
§ Child gets identical copies of the parent’s open file descriptors § Child has a different PID than the parent
¢ fork is interesting (and often confusing) because it is called once but returns twice
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
fork Example
int main() {
pid_t pid;
int x = 1;
pid = Fork();
if (pid == 0) { /* Child */
printf("child : x=%d\n", ++x);
/* Parent */
printf("parent: x=%d\n", --x);
¢ Call once, return twice
¢ Concurrent execution
§ Can’t predict execution order of parent and child
¢ Duplicate but separate address space
§xhas a value of 1 when fork returns in parent and child
§ Subsequent changes to x are independent
¢ Shared open files
§ stdout is the same in both parent and child
linux> ./fork
parent: x=0
child : x=2
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Modeling fork with Process Graphs
¢ A process graph is a useful tool for capturing the partial
ordering of statements in a concurrent program:
§ Each vertex is the execution of a statement
§ a -> b means a happens before b
§ Edges can be labeled with current value of variables § printf vertices can be labeled with output
§ Each graph begins with a vertex with no inedges
¢ Any topological sort of the graph corresponds to a feasible total ordering.
§ Total ordering of vertices where all edges point from left to right
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Process Graph Example
int main() {
pid_t pid;
int x = 1;
pid = Fork();
if (pid == 0) { /* Child */
printf(“child : x=%d\n”, ++x);
/* Parent */
printf(“parent: x=%d\n”, –x);
child: x=2
printf exit x==1 parent: x=0
main for printf exit k
Child Parent
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Interpreting Process Graphs ¢ Original graph:
child: x=2
printf exit
parent: x=0
main for printf k
¢ Relabled graph: abcd
Feasible total ordering:
abecfd Infeasible total ordering:
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
fork Example: Two consecutive forks Bye
void fork2()
fork printf
printf(“L0\n”);
printf(“L1\n”);
printf(“Bye\n”);
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
printf for printf fork printf k
Feasible output:
L0 L1 Bye Bye L1 Bye Bye
Infeasible output:
L0 Bye L1 Bye L1 Bye Bye
Sogang University
fork Example: Nested forks in parent
void fork4()
L0 L1 L2 Bye
printf(“L0\n”);
if (fork() != 0) {
printf(“L1\n”);
if (fork() != 0) {
printf(“L2\n”);
printf(“Bye\n”);
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
printf fork printf fork printf printf
Feasible output:
L0 L1 Bye Bye L2 Bye
Infeasible output:
L0 Bye L1 Bye Bye L2
Sogang University
fork Example: Nested forks in children
printf printf
void fork5()
printf(“L0\n”);
if (fork() == 0) {
printf(“L1\n”);
if (fork() == 0) {
printf(“L2\n”);
printf(“Bye\n”);
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
printf fork printf
Feasible output:
L0 Bye L1 L2 Bye Bye
Infeasible output:
L0 Bye L1 Bye Bye L2
print fork printf f
Sogang University
Reaping Child Processes
§ When process terminates, it still consumes system resources
§ Examples: Exit status, various OS tables § Called a “zombie”
§ Living corpse, half alive and half dead
§ Performed by parent on terminated child (using wait or waitpid) § Parent is given exit status information
§ Kernel then deletes zombie child process
¢ What if parent doesn’t reap?
§ If any parent terminates without reaping a child, then the orphaned
child will be reaped by init process (pid == 1)
§ So, only need explicit reaping in long-running processes
§ e.g., shells and servers
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Sogang University
Zombie Example
linux> ./forks 7 &
Running Parent, PID = 6639
Terminating linux> ps PID TTY
6585 ttyp9
6639 ttyp9
6640 ttyp9
Child, PID = 6640
00:00:00 tcsh
00:00:03 forks
00:00:00 forks
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com