0% found this document useful (0 votes)
6 views

Exceptions-signals

Uploaded by

navid.panah1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Exceptions-signals

Uploaded by

navid.panah1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Carnegie Mellon Carnegie Mellon

ECF Exists at All Levels of a System


Exceptional Control Flow:  Exceptions
Signals and Nonlocal Jumps  Hardware and operating system kernel software
 Process Context Switch Previous Lecture
 Hardware timer and kernel software
15‐213 / 18‐213: Introduction to Computer Systems
14th Lecture, Feb 28, 2013  Signals
 Kernel software and application software
Instructors:  Nonlocal jumps
 Application code
This Lecture
Seth Copen Goldstein, Anthony Rowe, and Greg Kesden

1 2

Carnegie Mellon Carnegie Mellon

Today The World of Multitasking


 Multitasking, shells  System runs many processes concurrently
 Signals
 Nonlocal jumps  Process: executing program
 State includes memory image + register values + program counter

 Regularly switches from one process to another


 Suspend process when it needs I/O resource or timer event occurs
 Resume process when I/O available or given scheduling priority

 Appears to user(s) as if all processes executing simultaneously


 Even though most systems can only execute one process at a time
 Except possibly with lower performance than if running alone

3 4
Carnegie Mellon Carnegie Mellon

Programmer’s Model of Multitasking Unix Process Hierarchy


 Basic functions
[0]
 fork spawns new process
 Called once, returns twice
 exit terminates own process init [1]
Called once, never returns
 Puts it into “zombie” status
 wait and waitpid wait for and reap terminated children Daemon Login shell
e.g. httpd
 execve runs new program in existing process
 Called once, (normally) never returns
Child Child Child

 Programming challenge
 Understanding the nonstandard semantics of the functions
Grandchild Grandchild
 Avoiding improper use of system resources
 E.g. “Fork bombs” can disable a system
5 6

Carnegie Mellon Carnegie Mellon

Simple Shell eval Function


Shell Programs void eval(char *cmdline) {
 A shell is an application program that runs programs on char *argv[MAXARGS]; /* argv for execve() */
int bg; /* should the job run in bg or fg? */
behalf of the user. pid_t pid; /* process id */
 sh Original Unix shell (Stephen Bourne, AT&T Bell Labs, 1977)
bg = parseline(cmdline, argv);
 csh BSD Unix C shell (tcsh: enhanced csh at CMU and elsewhere)
if (!builtin_command(argv)) {
 bash “Bourne‐Again” Shell if ((pid = Fork()) == 0) { /* child runs user job */
if (execve(argv[0], argv, environ) < 0) {
int main() { Execution is a sequence of printf("%s: Command not found.\n", argv[0]);
char cmdline[MAXLINE]; read/evaluate steps exit(0);
}
while (1) { }
/* read */
printf("> "); if (!bg) { /* parent waits for fg job to terminate */
Fgets(cmdline, MAXLINE, stdin); int status;
if (feof(stdin)) if (waitpid(pid, &status, 0) < 0)
exit(0); unix_error("waitfg: waitpid error");
}
/* evaluate */ else /* otherwise, don’t wait for bg job */
eval(cmdline); printf("%d %s", pid, cmdline);
} }
} }
7 8
Carnegie Mellon Carnegie Mellon

Simple Shell eval Function Simple Shell eval Function


void eval(char *cmdline) { void eval(char *cmdline) {
char *argv[MAXARGS]; /* argv for execve() */ char *argv[MAXARGS]; /* argv for execve() */
int bg; /* should the job run in bg or fg? */ int bg; /* should the job run in bg or fg? */
pid_t pid; /* process id */ pid_t pid; /* process id */

bg = parseline(cmdline, argv); bg = parseline(cmdline, argv);


if (!builtin_command(argv)) { if (!builtin_command(argv)) {
if ((pid = Fork()) == 0) { /* child runs user job */ if ((pid = Fork()) == 0) { /* child runs user job */
if (execve(argv[0], argv, environ) < 0) { if (execve(argv[0], argv, environ) < 0) {
printf("%s: Command not found.\n", argv[0]); printf("%s: Command not found.\n", argv[0]);
exit(0); exit(0);
} }
} }

if (!bg) { /* parent waits for fg job to terminate */ if (!bg) { /* parent waits for fg job to terminate */
int status; int status;
if (waitpid(pid, &status, 0) < 0) if (waitpid(pid, &status, 0) < 0)
unix_error("waitfg: waitpid error"); unix_error("waitfg: waitpid error");
} }
else /* otherwise, don’t wait for bg job */ else /* otherwise, don’t wait for bg job */
printf("%d %s", pid, cmdline); printf("%d %s", pid, cmdline);
} }
} }
9 10

Carnegie Mellon Carnegie Mellon

Simple Shell eval Function Simple Shell eval Function


void eval(char *cmdline) { void eval(char *cmdline) {
char *argv[MAXARGS]; /* argv for execve() */ char *argv[MAXARGS]; /* argv for execve() */
int bg; /* should the job run in bg or fg? */ int bg; /* should the job run in bg or fg? */
pid_t pid; /* process id */ pid_t pid; /* process id */

bg = parseline(cmdline, argv); bg = parseline(cmdline, argv);


if (!builtin_command(argv)) { if (!builtin_command(argv)) {
if ((pid = Fork()) == 0) { /* child runs user job */ if ((pid = Fork()) == 0) { /* child runs user job */
if (execve(argv[0], argv, environ) < 0) { if (execve(argv[0], argv, environ) < 0) {
printf("%s: Command not found.\n", argv[0]); printf("%s: Command not found.\n", argv[0]);
exit(0); exit(0);
} }
} }

if (!bg) { /* parent waits for fg job to terminate */ if (!bg) { /* parent waits for fg job to terminate */
int status; int status;
if (waitpid(pid, &status, 0) < 0) if (waitpid(pid, &status, 0) < 0)
unix_error("waitfg: waitpid error"); unix_error("waitfg: waitpid error");
} }
else /* otherwise, don’t wait for bg job */ else /* otherwise, don’t wait for bg job */
printf("%d %s", pid, cmdline); printf("%d %s", pid, cmdline);
} }
} }
11 12
Carnegie Mellon Carnegie Mellon

Simple Shell eval Function What Is a “Background Job”?


void eval(char *cmdline) {
char *argv[MAXARGS]; /* argv for execve() */
int bg; /* should the job run in bg or fg? */
 Users generally run one command at a time
pid_t pid; /* process id */  Type command, read output, type another command
bg = parseline(cmdline, argv);
if (!builtin_command(argv)) {
if ((pid = Fork()) == 0) { /* child runs user job */  Some programs run “for a long time”
if (execve(argv[0], argv, environ) < 0) {  Example: “delete this file in two hours”
printf("%s: Command not found.\n", argv[0]);
exit(0); unix> sleep 7200; rm /tmp/junk # shell stuck for 2 hours
}
}

if (!bg) { /* parent waits for fg job to terminate */


 A “background” job is a process we don't want to wait for
int status;
if (waitpid(pid, &status, 0) < 0) unix> (sleep 7200 ; rm /tmp/junk) &
unix_error("waitfg: waitpid error"); [1] 907
} unix> # ready for next command
else /* otherwise, don’t wait for bg job */
printf("%d %s", pid, cmdline);
}
}
13 14

Carnegie Mellon Carnegie Mellon

Problem with Simple Shell Example ECF to the Rescue!


 Our example shell correctly waits for and reaps foreground  Problem
jobs  The shell doesn't know when a background job will finish
 By nature, it could happen at any time
 But what about background jobs?  The shell's regular control flow can't reap exited background processes in
a timely fashion
 Will become zombies when they terminate
 Regular control flow is “wait until running job completes, then reap it”
 Will never be reaped because shell (typically) will not terminate
 Will create a memory leak that could run the kernel out of memory
 Modern Unix: once you exceed your process quota, your shell can't run  Solution: Exceptional control flow
any new commands for you: fork() returns ‐1  The kernel will interrupt regular processing to alert us when a background
process completes
unix> limit maxproc # csh syntax  In Unix, the alert mechanism is called a signal
maxproc 202752
unix> ulimit -u # bash syntax
202752

15 16
Carnegie Mellon Carnegie Mellon

Today Signals
 Multitasking, shells  A signal is a small message that notifies a process that an
event of some type has occurred in the system
 Signals
 akin to exceptions and interrupts
 Nonlocal jumps  sent from the kernel (sometimes at the request of another process) to a
process
 signal type is identified by small integer ID’s (1‐30)
 only information in a signal is its ID and the fact that it arrived

ID Name Default Action Corresponding Event


2 SIGINT Terminate Interrupt (e.g., ctl‐c from keyboard)
9 SIGKILL Terminate Kill program (cannot override or ignore)
11 SIGSEGV Terminate & Dump Segmentation violation
14 SIGALRM Terminate Timer signal
17 SIGCHLD Ignore Child stopped or terminated

17 18

Carnegie Mellon Carnegie Mellon

Sending a Signal Receiving a Signal


 Kernel sends (delivers) a signal to a destination process by  A destination process receives a signal when it is forced by
updating some state in the context of the destination process the kernel to react in some way to the delivery of the signal

 Kernel sends a signal for one of the following reasons:  Three possible ways to react:
 Kernel has detected a system event such as divide‐by‐zero (SIGFPE) or  Ignore the signal (do nothing)
the termination of a child process (SIGCHLD)  Terminate the process (with optional core dump)
 Another process has invoked the kill system call to explicitly request  Catch the signal by executing a user‐level function called signal handler
the kernel to send a signal to the destination process
 Akin to a hardware exception handler being called in response to an
asynchronous interrupt

19 20
Carnegie Mellon Carnegie Mellon

Pending and Blocked Signals Signal Concepts


 A signal is pending if sent but not yet received  Kernel maintains pending and blocked bit vectors in the
 There can be at most one pending signal of any particular type context of each process
 Important: Signals are not queued  pending: represents the set of pending signals
 If a process has a pending signal of type k, then subsequent signals of  Kernel sets bit k in pending when a signal of type k is delivered
type k that are sent to that process are discarded  Kernel clears bit k in pending when a signal of type k is received

 A process can block the receipt of certain signals  blocked: represents the set of blocked signals
 Blocked signals can be delivered, but will not be received until the signal  Can be set and cleared by using the sigprocmask function
is unblocked

 A pending signal is received at most once

No Counting!!!

21 22

Carnegie Mellon Carnegie Mellon

Process Groups Sending Signals with /bin/kill Program


 Every process belongs to exactly one process group  /bin/kill program
sends arbitrary signal to a linux> ./forks 16
Child1: pid=24818 pgrp=24817
pid=10
pgid=10 Shell process or process group Child2: pid=24819 pgrp=24817

linux> ps
 Examples PID TTY TIME CMD

pid=20 Fore‐ Back‐ Back‐  /bin/kill –9 24818 24788 pts/2 00:00:00 tcsh
pid=32 pid=40 24818 pts/2 00:00:02 forks
pgid=20 ground ground pgid=32 ground pgid=40 Send SIGKILL to process 24818 24819 pts/2 00:00:02 forks
job job #1 job #2
24820 pts/2 00:00:00 ps
Background Background  /bin/kill –9 –24817 linux> /bin/kill -9 -24817
linux> ps
process group 32 process group 40 Send SIGKILL to every process
Child Child PID TTY TIME CMD
in process group 24817 24788 pts/2 00:00:00 tcsh
pid=21 pid=22 getpgrp() 24823 pts/2 00:00:00 ps
pgid=20 pgid=20 Return process group of current process linux>
Foreground setpgid()
process group 20 Change process group of a process

23 24
Carnegie Mellon Carnegie Mellon

Sending Signals from the Keyboard Example of ctrl-c and ctrl-z


 Typing ctrl‐c (ctrl‐z) sends a SIGINT (SIGTSTP) to every job in the bluefish> ./forks 17 STAT (process state) Legend:
foreground process group. Child: pid=28108 pgrp=28107
 SIGINT – default action is to terminate each process Parent: pid=28107 pgrp=28107 First letter:
 SIGTSTP – default action is to stop (suspend) each process <types ctrl-z> S: sleeping
Suspended T: stopped
pid=10 bluefish> ps w R: running
pgid=10 Shell PID TTY STAT TIME COMMAND
27699 pts/8 Ss 0:00 -tcsh
28107 pts/8 T 0:01 ./forks 17 Second letter:
28108 pts/8 T 0:01 ./forks 17 s: session leader
Fore‐ Back‐ Back‐ 28109 pts/8 R+ 0:00 ps w +: foreground proc group
pid=20 pid=32 pid=40 bluefish> fg
pgid=20 ground ground pgid=32 ground pgid=40
job job #1 job #2 ./forks 17 See “man ps” for more
<types ctrl-c> details
Background Background bluefish> ps w
process group 32 process group 40 PID TTY STAT TIME COMMAND
Child Child 27699 pts/8 Ss 0:00 -tcsh
28110 pts/8 R+ 0:00 ps w
pid=21 pid=22
pgid=20 pgid=20

Foreground
process group 20
25 26

Carnegie Mellon Carnegie Mellon

Sending Signals with kill Function Sending Signals with kill Function
void fork12() void fork12()
{ {
pid_t pid[N]; pid_t pid[N];
int i, child_status; int i, child_status;
for (i = 0; i < N; i++) for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0) if ((pid[i] = fork()) == 0)
while(1); /* Child infinite loop */ while(1); /* Child infinite loop */

/* Parent terminates the child processes */ /* Parent terminates the child processes */
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
printf("Killing process %d\n", pid[i]); printf("Killing process %d\n", pid[i]);
kill(pid[i], SIGINT); kill(pid[i], SIGINT);
} }

/* Parent reaps terminated children */ /* Parent reaps terminated children */


for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
pid_t wpid = wait(&child_status); pid_t wpid = wait(&child_status);
if (WIFEXITED(child_status)) if (WIFEXITED(child_status))
printf("Child %d terminated with exit status %d\n", printf("Child %d terminated with exit status %d\n",
wpid, WEXITSTATUS(child_status)); wpid, WEXITSTATUS(child_status));
else else
printf("Child %d terminated abnormally\n", wpid); printf("Child %d terminated abnormally\n", wpid);
} }
} }

27 28
Carnegie Mellon Carnegie Mellon

Sending Signals with kill Function Sending Signals with kill Function
void fork12() void fork12()
{ {
pid_t pid[N]; pid_t pid[N];
int i, child_status; int i, child_status;
for (i = 0; i < N; i++) for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0) if ((pid[i] = fork()) == 0)
while(1); /* Child infinite loop */ while(1); /* Child infinite loop */

/* Parent terminates the child processes */ /* Parent terminates the child processes */
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
printf("Killing process %d\n", pid[i]); printf("Killing process %d\n", pid[i]);
kill(pid[i], SIGINT); kill(pid[i], SIGINT);
} }

/* Parent reaps terminated children */ /* Parent reaps terminated children */


for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
pid_t wpid = wait(&child_status); pid_t wpid = wait(&child_status);
if (WIFEXITED(child_status)) if (WIFEXITED(child_status))
printf("Child %d terminated with exit status %d\n", printf("Child %d terminated with exit status %d\n",
wpid, WEXITSTATUS(child_status)); wpid, WEXITSTATUS(child_status));
else else
printf("Child %d terminated abnormally\n", wpid); printf("Child %d terminated abnormally\n", wpid);
} }
} }

29 30

Carnegie Mellon Carnegie Mellon

Sending Signals with kill Function Sending Signals with kill Function
void fork12() void fork12()
{ {
pid_t pid[N]; pid_t pid[N];
int i, child_status; int i, child_status;
for (i = 0; i < N; i++) for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0) if ((pid[i] = fork()) == 0)
while(1); /* Child infinite loop */ while(1); /* Child infinite loop */

/* Parent terminates the child processes */ /* Parent terminates the child processes */
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
printf("Killing process %d\n", pid[i]); printf("Killing process %d\n", pid[i]);
kill(pid[i], SIGINT); kill(pid[i], SIGINT);
} }

/* Parent reaps terminated children */ /* Parent reaps terminated children */


for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
pid_t wpid = wait(&child_status); pid_t wpid = wait(&child_status);
if (WIFEXITED(child_status)) if (WIFEXITED(child_status))
printf("Child %d terminated with exit status %d\n", printf("Child %d terminated with exit status %d\n",
wpid, WEXITSTATUS(child_status)); wpid, WEXITSTATUS(child_status));
else else
printf("Child %d terminated abnormally\n", wpid); printf("Child %d terminated abnormally\n", wpid);
} }
} }

31 32
Carnegie Mellon Carnegie Mellon

Receiving Signals Receiving Signals


 Suppose kernel is returning from an exception handler  Suppose kernel is returning from an exception handler
and is ready to pass control to process p and is ready to pass control to process p

Process A Process B  Kernel computes pnb = pending & ~blocked


 The set of pending nonblocked signals for process p
user code

kernel code context switch


 If (pnb == 0)
Time user code  Pass control to next instruction in the logical flow for p
kernel code context switch  Else
user code  Choose least nonzero bit k in pnb and force process p to receive
signal k
 The receipt of the signal triggers some action by p
Important: All context switches are initiated by calling  Repeat for all nonzero k in pnb
some exceptional hander.  Pass control to next instruction in logical flow for p
33 34

Carnegie Mellon Carnegie Mellon

Default Actions Installing Signal Handlers


 The signal function modifies the default action associated
 Each signal type has a predefined default action, which is
with the receipt of signal signum:
one of:
 handler_t *signal(int signum, handler_t *handler)
 The process terminates
 The process terminates and dumps core
 The process stops until restarted by a SIGCONT signal  Different values for handler:
 The process ignores the signal  SIG_IGN: ignore signals of type signum
 SIG_DFL: revert to the default action on receipt of signals of type signum
 Otherwise, handler is the address of a signal handler
 Called when process receives signal of type signum
 Referred to as “installing” the handler
 Executing handler is called “catching” or “handling” the signal
 When the handler executes its return statement, control passes back
to instruction in the control flow of the process that was interrupted
by receipt of the signal
35 36
Carnegie Mellon Carnegie Mellon

Signal Handling Example Signal Handling Example


void int_handler(int sig) { void int_handler(int sig) {
safe_printf("Process %d received signal %d\n", getpid(), sig); safe_printf("Process %d received signal %d\n", getpid(), sig);
exit(0); exit(0);
} }

void fork13() { void fork13() {


pid_t pid[N]; pid_t pid[N];
int i, child_status; int i, child_status;
signal(SIGINT, int_handler); signal(SIGINT, int_handler);
for (i = 0; i < N; i++) linux> ./forks 13 for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0)Killing
{ process 25417 if ((pid[i] = fork()) == 0) {
Killing
while(1); /* child infinite process 25418
loop while(1); /* child infinite loop
} Killing process 25419 }
for (i = 0; i < N; i++) { Killing process 25420 for (i = 0; i < N; i++) {
Killing
printf("Killing process %d\n", process 25421
pid[i]); printf("Killing process %d\n", pid[i]);
kill(pid[i], SIGINT); Process 25417 received signal 2 kill(pid[i], SIGINT);
} Process 25418 received signal 2 }
for (i = 0; i < N; i++) { Process 25420 received signal 2 for (i = 0; i < N; i++) {
Process 25421 received signal 2
pid_t wpid = wait(&child_status); pid_t wpid = wait(&child_status);
Process 25419 received signal 2
if (WIFEXITED(child_status)) if (WIFEXITED(child_status))
Child with
printf("Child %d terminated 25417 terminated
exit with exit
status %d\n", status 0 printf("Child %d terminated with exit status %d\n",
Child 25418 terminated with exit
wpid, WEXITSTATUS(child_status)); status 0 wpid, WEXITSTATUS(child_status));
else Child 25420 terminated with exit status 0 else
Child abnormally\n",
printf("Child %d terminated 25419 terminated with exit
wpid); status 0 printf("Child %d terminated abnormally\n", wpid);
} Child 25421 terminated with exit status 0 }
} linux> }
37 38

Carnegie Mellon Carnegie Mellon

Signal Handling Example Signal Handling Example


void int_handler(int sig) { void int_handler(int sig) {
safe_printf("Process %d received signal %d\n", getpid(), sig); safe_printf("Process %d received signal %d\n", getpid(), sig);
exit(0); exit(0);
} }

void fork13() { void fork13() {


pid_t pid[N]; pid_t pid[N];
int i, child_status; int i, child_status;
signal(SIGINT, int_handler); signal(SIGINT, int_handler);
for (i = 0; i < N; i++) for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0) { if ((pid[i] = fork()) == 0) {
while(1); /* child infinite loop while(1); /* child infinite loop
} }
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
printf("Killing process %d\n", pid[i]); printf("Killing process %d\n", pid[i]);
kill(pid[i], SIGINT); kill(pid[i], SIGINT);
} }
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
pid_t wpid = wait(&child_status); pid_t wpid = wait(&child_status);
if (WIFEXITED(child_status)) if (WIFEXITED(child_status))
printf("Child %d terminated with exit status %d\n", printf("Child %d terminated with exit status %d\n",
wpid, WEXITSTATUS(child_status)); wpid, WEXITSTATUS(child_status));
else else
printf("Child %d terminated abnormally\n", wpid); printf("Child %d terminated abnormally\n", wpid);
} }
} }
39 40
Carnegie Mellon Carnegie Mellon

Signal Handling Example Signal Handling Example


void int_handler(int sig) { void int_handler(int sig) {
safe_printf("Process %d received signal %d\n", getpid(), sig); safe_printf("Process %d received signal %d\n", getpid(), sig);
exit(0); exit(0);
} }

void fork13() { void fork13() {


pid_t pid[N]; pid_t pid[N];
int i, child_status; int i, child_status;
signal(SIGINT, int_handler); signal(SIGINT, int_handler);
for (i = 0; i < N; i++) for (i = 0; i < N; i++)
if ((pid[i] = fork()) == 0) { if ((pid[i] = fork()) == 0) {
while(1); /* child infinite loop while(1); /* child infinite loop
} }
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
printf("Killing process %d\n", pid[i]); printf("Killing process %d\n", pid[i]);
kill(pid[i], SIGINT); kill(pid[i], SIGINT);
} }
for (i = 0; i < N; i++) { for (i = 0; i < N; i++) {
pid_t wpid = wait(&child_status); pid_t wpid = wait(&child_status);
if (WIFEXITED(child_status)) if (WIFEXITED(child_status))
printf("Child %d terminated with exit status %d\n", printf("Child %d terminated with exit status %d\n",
wpid, WEXITSTATUS(child_status)); wpid, WEXITSTATUS(child_status));
else else
printf("Child %d terminated abnormally\n", wpid); printf("Child %d terminated abnormally\n", wpid);
} }
} }
41 42

Carnegie Mellon Carnegie Mellon

Signal Handling Example Signals Handlers as Concurrent Flows


void int_handler(int sig) {
safe_printf("Process %d received signal %d\n", getpid(), sig);
exit(0);  A signal handler is a separate logical flow (not process) that
}
runs concurrently with the main program
void fork13() {
pid_t pid[N];
 “concurrently” in the “not sequential” sense
int i, child_status;
signal(SIGINT, int_handler);
for (i = 0; i < N; i++) linux> ./forks 13
if ((pid[i] = fork()) == 0)Killing
{ process 25417 Process A Process A Process B
Killing
while(1); /* child infinite process 25418
loop
} Killing process 25419 while (1) handler(){
for (i = 0; i < N; i++) { Killing process 25420
; …
Killing
printf("Killing process %d\n", process 25421
pid[i]);
Process 25417 received signal 2 }
kill(pid[i], SIGINT);
} Process 25418 received signal 2
for (i = 0; i < N; i++) { Process 25420 received signal 2
Process 25421 received signal 2
pid_t wpid = wait(&child_status);
Process 25419 received signal 2
Time
if (WIFEXITED(child_status))
Child with
printf("Child %d terminated 25417 terminated
exit with exit
status %d\n", status 0
Child 25418 terminated with exit
wpid, WEXITSTATUS(child_status)); status 0
else Child 25420 terminated with exit status 0
Child abnormally\n",
printf("Child %d terminated 25419 terminated with exit
wpid); status 0
} Child 25421 terminated with exit status 0
} linux>
43 44
Carnegie Mellon Carnegie Mellon

Another View of Signal Handlers as Signal Handler Funkiness


Concurrent Flows int ccount = 0;  Pending signals are not
void child_handler(int sig) queued
{
int child_status;  For each signal type, just
Process A Process B pid_t pid = wait(&child_status); have single bit indicating
ccount--;
whether or not signal is
safe_printf(
Signal delivered Icurr user code (main) "Received signal %d from process %d\n", pending
sig, pid);
kernel code context switch }
 Even if multiple processes
user code (main) void fork14() have sent this signal
{
kernel code context switch pid_t pid[N];
Signal received int i, child_status;
user code (handler) ccount = N;
signal(SIGCHLD, child_handler);
kernel code for (i = 0; i < N; i++)
linux> ./forks 14
Inext if ((pid[i] = fork()) == 0) SIGCHLD
Received { signal 17 for process 21344
user code (main) sleep(1); /* deschedule child */
Received SIGCHLD signal 17 for process 21345
exit(0); /* Child: Exit */
}
while (ccount > 0)
pause(); /* Suspend until signal occurs */
}
45 46

Carnegie Mellon Carnegie Mellon

Living With Nonqueuing Signals More Signal Handler Funkiness


 Must check for all terminated jobs  Signal arrival during long system calls (say a read)
 Typically loop with waitpid  Signal handler interrupts read call
void child_handler2(int sig)  Linux: upon return from signal handler, the read call is restarted
{ automatically
int child_status;
pid_t pid;  Some other flavors of Unix can cause the read call to fail with an
while ((pid = waitpid(-1, &child_status, WNOHANG)) > 0) { EINTR error number (errno)
ccount--; in this case, the application program can restart the slow system call
safe_printf("Received signal %d from process %d\n",
sig, pid);
}
}
greatwhite> forks 15  Subtle differences like these complicate the writing of
void fork15() Received signal 17 from process 27476
{
portable code that uses signals
Received signal 17 from process 27477
. . . Received signal 17 from process 27478  Consult your textbook for details
signal(SIGCHLD, child_handler2);
Received signal 17 from process 27479
. . . Received signal 17 from process 27480
} greatwhite>
47 48
Carnegie Mellon Carnegie Mellon

A Program That Reacts to A Program That Reacts to Internally


Externally Generated Events (Ctrl‐c) Generated Events
#include <stdlib.h> #include <stdio.h> main() {
#include <stdio.h> #include <signal.h> signal(SIGALRM, handler);
#include <signal.h> alarm(1); /* send SIGALRM in
int beeps = 0; 1 second */
void handler(int sig) {
safe_printf("You think hitting ctrl-c will stop the bomb?\n"); /* SIGALRM handler */ while (1) {
sleep(2); void handler(int sig) { /* handler returns here */
safe_printf("Well..."); safe_printf("BEEP\n"); }
linux> ./external
sleep(1); }
<ctrl-c>
printf("OK\n"); if (++beeps < 5)
You think hitting ctrl-c will stop
exit(0); alarm(1);
the bomb? linux> ./internal
} else {
Well...OK BEEP
safe_printf("BOOM!\n"); BEEP
linux>
main() { exit(0); BEEP
signal(SIGINT, handler); /* installs ctl-c handler */ } BEEP
while(1) { } BEEP
}
internal.c BOOM!
}
bass>
external.c
49 50

Carnegie Mellon Carnegie Mellon

Async‐Signal‐Safety Today
 Function is async‐signal‐safe if either reentrant (all variables  Multitasking, shells
stored on stack frame, CS:APP2e 12.7.2) or non‐interruptible  Signals
by signals.  Nonlocal jumps
 Posix guarantees 117 functions to be async‐signal‐safe
 write is on the list, printf is not
 One solution: async‐signal‐safe wrapper for printf:

void safe_printf(const char *format, ...) {


char buf[MAXS];
va_list args;

va_start(args, format); /* reentrant */


vsnprintf(buf, sizeof(buf), format, args); /* reentrant */
va_end(args); /* reentrant */
write(1, buf, strlen(buf)); /* async-signal-safe */
}
safe_printf.c 51 52
Carnegie Mellon Carnegie Mellon

Nonlocal Jumps: setjmp/longjmp setjmp/longjmp (cont)


 Powerful (but dangerous) user‐level mechanism for  void longjmp(jmp_buf j, int i)
transferring control to an arbitrary location  Meaning:
 Controlled to way to break the procedure call / return discipline  return from the setjmp remembered by jump buffer j again ...
 Useful for error recovery and signal handling  … this time returning i instead of 0
 Called after setjmp
 int setjmp(jmp_buf j)  Called once, but never returns
 Must be called before longjmp
 Identifies a return site for a subsequent longjmp
 Called once, returns one or more times  longjmp Implementation:
 Restore register context (stack pointer, base pointer, PC value) from
 Implementation: jump buffer j
 Remember where you are by storing the current register context,  Set %eax (the return value) to i
stack pointer, and PC value in jmp_buf  Jump to the location indicated by the PC stored in jump buf j
 Return 0

53 54

Carnegie Mellon Carnegie Mellon

setjmp/longjmp Example Limitations of Nonlocal Jumps


 Works within stack discipline
#include <setjmp.h>
jmp_buf buf;
 Can only long jump to environment of function that has been called
but not yet completed
Before longjmp After longjmp
main() { jmp_buf env; env
if (setjmp(buf) != 0) { P1 P1
printf("back in main due to an error\n"); P1()
else {
printf("first time through\n"); if (setjmp(env)) { P2
p1(); /* p1 calls p2, which calls p3 */ /* Long Jump to here */
} } else {
... P2();
P2
p3() { }
<error checking code> }
if (error) P2
longjmp(buf, 1) P2()
} { . . . P2(); . . . P3(); } P3
P3()
{
longjmp(env, 1);
}
55 56
Carnegie Mellon Carnegie Mellon

Limitations of Long Jumps (cont.) Putting It All Together: A Program


 Works within stack discipline That Restarts Itself When ctrl-c’d
 Can only long jump to environment of function that has been called #include <stdio.h>
#include <signal.h>
but not yet completed #include <setjmp.h>
P1 greatwhite> ./restart
jmp_buf env; sigjmp_buf buf; starting
processing...
P1() P2 void handler(int sig) { processing...
{ env siglongjmp(buf, 1); processing...
P2(); P3(); }
At setjmp restarting
} Ctrl‐c
main() { processing...
signal(SIGINT, handler); processing...
P2() P1 restarting
{ if (!sigsetjmp(buf, 1)) processing... Ctrl‐c
if (setjmp(env)) { env printf("starting\n"); processing...
/* Long Jump to here */ X P2 else processing...
} printf("restarting\n");
} P2 returns P1 while(1) {
sleep(1);
P3() env printf("processing...\n");
{ X P3 }
longjmp(env, 1); } restart.c
} At longjmp
57 58

Carnegie Mellon Carnegie Mellon

Summary Midterm Exam info


 Signals provide process‐level exception handling
 Midterm on 3/5 at 6:30 for everyone
 Can generate from user programs
 Can define effect by declaring signal handler
 Lastname starts with
 A‐J ‐> Wh 7500
 Some caveats
 K‐Z ‐> Rashid
 Very high overhead
>10,000 clock cycles
 Covers all material through today
 Only use for exceptional conditions  Review on Sunday at 3pm at Dh2315 and Dh2210
 Don’t have queues  Recitation will also do midterm review on Monday
 Just one bit for each pending signal type

 Nonlocal jumps provide exceptional control flow within


process
 Within constraints of stack discipline

59 60

You might also like