UNIX Signals
UNIX Signals
Signals
Overview
1. 2. 3. 4. 5. 6. Definition Signal Types Generating a Signal Responding to a Signal Common Uses of Signals Timeout on a read()
continued
1. Definition
A
signal is an asynchronous event which is delivered to a process. means that the event can occur at any time
may be unrelated to the execution of the process e.g. user types ctrl-C, or the modem hangs
4
Asynchronous
Name
SIGINT SIGQUIT SIGKILL SIGSEGV SIGPIPE SIGALRM SIGUSR1 SIGUSR2
Description
Interrupt character typed Quit character typed (^\) kill -9 Invalid memory reference Write on pipe but no reader alarm() clock rings user-defined signal type user-defined signal type
Default Action
terminate process create core image terminate process create core image terminate process terminate process terminate process terminate process
Signal Sources
shell command terminal driver
SIGINT SIGKILL SIGPIPE SIGWINCH SIGALRM SIGHUP SIGQUIT
memory management
kernel
window manager
a process
SIGUSR1
3. Generating a Signal
Use
check
ps
might be better.
7
kill()
Send
Return
0 if ok, -1 on error.
8
Meaning
send signal to process pid send signal to all processes whose process group ID equals the senders pgid.
e.g. parent kills all children
9
>0 == 0
4. Responding to a Signal
A
process can:
ignore/discard the signal (not possible with SIGKILL or SIGSTOP) execute a signal handler function, and then possibly resume execution or terminate carry out the default action for that signal
The
Actual Prototype
The actual prototype, listed in the man page is a bit perplexing but is an expansion of the Sigfunc type:
void (*signal(int signo, void(*handler)(int)))(int);
In Linux:
typedef void (*sighandler_t)(int);
sig_handler_t signal(int signo, sighandler_t handler);
12
The signal function itself returns a pointer to a function. The return type is the same The signal to behandler function as the function that is passed in, The i.e.,aUse the signal handling caught or ignored function that takes an signal.h library: Receives a single integer int and returns a void is given as argument and returns void Argument
Signal Handling
#include <signal.h>
sig
The function to be called is a function when the specified signal Signal #include <signal.h> typedef void Sigfunc(int); /* my defn */ The given as a that takes two *signal( int signo,is received is returned function Sigfunc Sigfunc *handler ); pointer totakes a integer the function arguments: handler parameter. sig and handler
13
Example
int main() { signal( SIGINT, foo ); : /* do usual things until SIGINT */ return 0; } void foo( int signo ) { : /* deal with SIGINT signal */ return; } /* return to program */
14
sig_examp.c
#include <stdio.h> #include <unistd.h> #include <signal.h> void sig_usr( int signo ); /* handles two signals */
int main() { int i = 0; if( signal( SIGUSR1,sig_usr ) == SIG_ERR ) printf( Cannot catch SIGUSR1\n ); if( signal( SIGUSR2,sig_usr ) == SIG_ERR ) printf(Cannot catch SIGUSR2\n); :
continued
15
:
while(1) { printf( %2d\n, I ); pause(); /* pause until signal handler * has processed signal */ i++; } return 0;
continued
16
void sig_usr( int signo ) /* argument is signal number */ { if( signo == SIGUSR1 ) printf(Received SIGUSR1\n); else if( signo == SIGUSR2 ) printf(Received SIGUSR2\n); else printf(Error: received signal %d\n, signo);
return;
}
17
Usage
$ sig_examp & [1] 4720 0 $ kill -USR1 4720 Received SIGUSR1 1 $ kill -USR2 4720 Received SIGUSR2 2 $ kill 4720 [1] + Terminated $
Meaning
Ignore / discard the signal.
SIG_DFL
SIG_ERR
19
Multiple Signals
If
many signals of the same type are waiting to be handled (e.g. two SIGINTs), then most UNIXs will only deliver one of them.
the others are thrown away
If
many signals of different types are waiting to be handled (e.g. a SIGINT, SIGSEGV, SIGUSR1), they are not delivered in any fixed order.
20
pause()
returned.
21
Linux (and many other UNIXs), the signal disposition in a process is reset to its default action immediately after the signal has been delivered.
Must
Reset Problem
:
void ouch( int sig ) { printf( "OUCH! - I got signal %d\n", sig ); (void) signal(SIGINT, ouch); } Problem: from the time int main() that the interrupt function starts to just before the { signal handler is re-established (void) signal( SIGINT, the signal will not be ouch ); while(1) handled. { printf("Hello World!\n"); sleep(1); If another SIGINT signal is received during this time, } default behavior will be done, } i.e., program will terminate.24
To keep catching the signal with this function, must call the signal system call again.
is a (very) small time period in foo() when a new SIGINT signal will cause the default action to be carried out -- process termination. there is no answer to this
With signal()
problem.
POSIX signal functions solve it (and some other later UNIXs)
25
27
28
void clean_up(int signo) { unlink(/tmp/work-file); kill(my_children_pids, SIGTERM); wait((int *)0); fprintf(stderr, Program terminated\n); exit(1); }
29
Problems
If
a program is run in the background then the interrupt and quit signals (SIGINT, SIGQUIT) are automatically ignored.
code should not override these changes:
check if the signal dispositions are SIG_IGN
Your
30
: if( signal(SIGINT, SIG_IGN ) != SIG_IGN ) signal(SIGINT, clean_up); if( signal(SIGQUIT, SIG_IGN ) != SIG_IGN ) signal(SIGQUIT, clean_up); :
Note: cannot check the signal disposition without changing it (sigaction that we will look at later , is different)
31
/* dummy argument */
33
Problems
Reset
problem interruption
Handler
void print_status(int signo) { signal(SIGUSR1, print_status); printf(%d blocks copied\n, count); return; }
Reset
problem count value not always defined. Must use global variables for status information
36
38
6.1. alarm()
6.2. Bad read() Timeout 6.3. setjmp() and longjmp() 6.4. Better read() Timeout
40
6.1. alarm()
Set
Returns
process can have at most one alarm timer running at once. is called when there is an existing alarm set then it returns the number of seconds remaining for the old alarm, and sets the timer to the new alarm value.
What do we do with the old alarm value?
If alarm()
An alarm(0)
continued
43
if( signal(SIGALRM, sig_alrm) == SIG_ERR ) { printf(signal(SIGALRM) error\n); exit(1); } alarm(10); n = read( 0, line, MAXLINE ); alarm(0); if( n < 0 ) /* read error */ fprintf( stderr, \nread error\n ); else write( 1, line, n ); return 0; } continued
44
45
Problems
The code assumes that the read() call terminates with an error after being interrupted ( talk about this later). Race Conditon: The kernel may take longer than 10 seconds to start the read() after the alarm() call.
the alarm may ring before the read() starts then the read() is not being timed; may block forever Two ways two solve this:
setjmp sigprocmask and sigsuspend
46
Prototypes
Returns
Behavior
In
the setjmp() call, env is initialized to information about the current state of the stack.
The longjmp()
call causes the stack to be reset to its env value. restarts after the setjmp() call, but this time setjmp() returns val.
49
Execution
Example
: jmp_buf env; int main() { char line[MAX]; int errval; /* global */
continued
50
: void process_line( char * ptr ) { : cmd_add() : } void cmd_add() { int token; token = get_token(); if( token < 0 ) /* bad error */ longjmp( env, 1 ); /* normal processing */ } int get_token() { if( some error ) longjmp( env, 2 ); }
51
52
sleep1()
#include <signal.h> #include <unistd.h>
void sig_alrm( int signo ) { return; /* return to wake up pause */ } unsigned int sleep1( unsigned int nsecs ) { if( signal( SIGALRM, sig_alrm ) == SIG_ERR ) return (nsecs); alarm( nsecs ); /* starts timer */ pause(); /* next caught signal wakes */ return( alarm( 0 ) ); /* turn off timer, return unslept * time */ }
54
sleep2()
static void jmp_buf env_alrm; void sig_alrm( int signo ) { longjmp( env_alrm, 1 ); } unsigned int sleep2( unsigned int { if( signal( SIGALRM, sig_alrm return (nsecs); if( setjmp( env_alrm) == 0 ) { alarm( nsecs ); /* pause(); /* } return( alarm( 0 ) ); }
nsecs )
) == SIG_ERR )
continued
55
fixes race condition. Even if the pause is never executed. is one more problem (will talk about that after fixing the earlier read function)
There
56
Status of Variables?
The
global and static variable values will not be changed by the longjmp() call
Nothing
is specified about local variables, are they rolled back to their original values (at the setjmp call) as the stack?
they may be restored to their values at the first setjmp(), but maybe not
Most
#define MAXLINE 512 void sig_alrm( int signo ); jmp_buf env_alrm; int main() { int n; char line[MAXLINE]; : continued
58
if( n < 0 ) /* read error */ fprintf( stderr, \nread error\n ); else write( 1, line, n ); return 0;
}
continued
60
void sig_alrm(int signo) /* interrupt the read() and jump to setjmp() call with value 1 */ { longjmp(env_alrm, 1); }
61
62
A Problem Remains!
If
63
The
POSIX signal system, uses signal sets, to deal with pending signals that might otherwise be missed while a signal is being processed
65
signal set stores collections of signal types. are used by signal functions to define which signal types are to be processed. contains several functions for creating, changing and examining signal sets.
66
Sets
POSIX
Prototypes
#include <signal.h>
67
7.2. sigprocmask()
A
process uses a signal set to create a mask which defines the signals it is blocking from delivery. good for critical sections where you want to block certain signals.
#include <signal.h> int sigprocmask( int how, const sigset_t *set, sigset_t *oldset); how indicates how mask is modified
68
how Meanings
Value SIG_BLOCK
Meaning
set signals are added to mask
SIG_UNBLOCK
SIG_SETMASK
69
7.3. sigaction()
Supercedes
#include <signal.h>
int sigaction(int signo, const struct sigaction *act, struct sigaction *oldact );
71
sigaction Structure
struct sigaction { void (*sa_handler)( int ); /* action to be taken or SIG_IGN, SIG_DFL */ sigset_t sa_mask; /* additional signal to be blocked */ int sa_flags; /* modifies action of the signal */ void (*sa_sigaction)( int, siginfo_t *, void * ); }
sa_flags
SIG_DFL reset handler to default upon return SA_SIGINFO denotes extra information is passed to handler (.i.e. specifies the use of the second handler in the structure.
72
sigaction() Behavior
A signo signal causes the sa_handler signal handler to be called. While sa_handler executes, the signals in sa_mask are blocked. Any more signo signals are also blocked.
sa_handler remains installed until it is changed by another sigaction() call. No reset problem.
73
Signal Raising
int main() { struct sigaction act; act.sa_handler = ouch;
struct sigaction
sigemptyset( &act.sa_mask );
act.sa_flags = 0;
sigaction( SIGINT, &act, 0 ); No flags are needed here. Possible flags include: We can manipulate while(1) SA_NOCLDSTOP sets of signals.. { SA_RESETHAND printf("Hello World!\n"); SA_RESTART This call sets the signal SA_NODEFER sleep(1); handler for the SIGINT } (ctrl-C) signal }
74
Signal Raising
To
sigexPOS.c
/* sigexPOS.c - demonstrate sigaction() */ /* include files as before */ int main(void) { /* struct to deal with action on signal set */ static struct sigaction act; void catchint(int); /* user signal handler */ /* set up action to take on receipt of SIGINT */ act.sa_handler = catchint;
76
/* create full set of signals */ sigfillset(&(act.sa_mask)); /* before sigaction call, SIGINT will terminate * process */ /* now, SIGINT will cause catchint to be executed */ sigaction( SIGINT, &act, NULL ); sigaction( SIGQUIT, &act, NULL ); printf("sleep call #1\n"); sleep(1); /* rest of program as before */
77
Other than SIGKILL and SIGSTOP, signals can be ignored: Instead of in the previous program:
act.sa_handler = catchint /* or whatever */ We use: act.sa_handler = SIG_IGN; The ^C key will be ignored
78
A Basic signal()
#include <signal.h> Sigfunc *signal( int signo, Sigfunc *func ) { struct sigaction act, oact; act.sa_handler = func; sigemptyset( &act.sa_mask ); act.sa_flags = 0; act.sa_flags |= SA_INTERRUPT; if( signo != SIGALRM ) act.sa_flags |= SA_RESTART; /* any system call interrupted by a signal * other than alarm is restarted */ if( sigaction( signo, &act, &oact) < 0 ) return(SIG_ERR); return( oact.sa_handler ); }
80
jump functions for use in signal handlers which handle masks correctly
sigsuspend()
NOTES (setjmp, sigjmp) POSIX does not specify whether setjmp will save the signal context. (In SYSV it will not. In BSD4.3 it will, and there is a function _setjmp that will not.) If you want to save signal masks, use sigsetjmp.
82
Example
#include <stdio.h> #include <signal.h> #include <setjmp.h> sigjmp_buf buf; void handler(int sig) { siglongjmp(buf, 1); } main() { signal(SIGINT, handler); if( sigsetjmp(buf, 1) == 0 ) printf("starting\n"); else printf("restarting\n"); } while(1) { sleep(5); printf( waiting...\n"); }
> a.out starting waiting... waiting... restarting waiting... waiting... waiting... restarting waiting... restarting waiting... waiting...
Control-c
Control-c Control-c
83
When a system call (e.g. read()) is interrupted by a signal, a signal handler is called, returns, and then what? On many UNIXs, slow system function calls do not resume. Instead they return an error and errno is assigned EINTR.
true of Linux, but can be altered with (Linux-specific) siginterrupt()
84
system functions carry out I/O on things that can possibly block the caller forever:
pipes, terminal drivers, networks some IPC functions pause(), some uses of ioctl()
Can
use signals on slow system functions to code up timeouts (e.g. did earlier )
85
Most system functions are non-slow, including ones that do disk I/O
e.g. read() of a disk file read() is sometimes a slow function, sometimes not
Some UNIXs resume non-slow system functions after the handler has finished. Some UNIXs only call the handler after the nonslow system function call has finished.
86
If a system function is called inside a signal handler then it may interact with an interrupted call to the same function in the main code.
e.g. malloc()
Non-reentrant Functions
A functions may be non-reentrant (only one call to it at once) for a number of reasons:
it uses a static data structure
errno Problem
variable.
Its
value in the program can be changed suddenly by a signal handler which produces a new system function error.
89