Tuesday, August 15, 2006

Unix Signal Handling

Some good links -
http://www.tldp.org/LDP/lpg/node138.html
http://www.enderunix.org/simsek/articles/signals.pdf
http://www.cs.ucsb.edu/~almeroth/classes/W99.276/assignment1/signals.html
http://www.opengroup.org/onlinepubs/007908799/xsh/sigaction.html

What are Signals

Signals are a means by which a process or a thread can be notified of a particular event. This is very similar to hardware interrupts where a partiular hardware state is notified to the operating system by raising an interrupt and the OS then performs the interrupt handler. The difference in this case being that instead of hardware telling the OS, it is the OS telling the process.

There are typically two kinds of signals -

  • Synchronous signals - also referred to as Traps. This typically occurs as a result of the current execution stream, where an unrecoverable error such as illegal memory access or divide by zero causes a trap into a kernel trap handler which then get delivered to the currently executing thread.
  • Asynchronous signals - these are as a result of external and unrelated events, such as another process sending using the kill to send this process a signal, or the user performing job control operations such as putting the process to sleep. In this case, the signal is delivered to the process and if an explicit disposition is instructed, then it is delivered to the first unblocked thread available.
All signals have a name and a number.

Following conditions generate signals -

  • Job-Control operations such as Ctrl-C, Ctrl-Z etc
  • Traps such as divide by zero, invalid memory reference
  • kill() system call
  • Kernel sending expicit signals on certain events to which the process should respond such as SIGPIPE is generated when process writes to pipe
When a signal occurs due to whatever reasons, it is said to be generated. At this time, determination is made whether the signal needs to be delivered to a specfic thread or to the process. Synchronous signals obviously go to the thread that caused it, while the asynchrounous signals go to the process. Every signal has a signal disposition. Signal disposition is actually the way in which the process would handle it. The signal disposition could be

  • Ignore the signal
  • Call a specific signal handler in the process
  • Apply the default action
By default, the default action would be applied. Typically, depending on the signal, the process could

  • Exit
  • Dump Core
  • Stop (suspend)
  • Ignore
An important point here is that the disposition for a signal is shared by all the threads in the process. When a signal's disposition is applied, the signal is said to be delivered. A signal can also be accepted by the process by having some thread wait for the signal by using the sigwait() function. Between the time the signal is generated and delivered or accepted, the signal is said to be pending.

It is also possible for a process to block the signal from being delivered and when that happens, the signal remains in the pending state until either the signal is ignored or unblocked. In a single threaded applications, this is done by applying a mask for the process. In a multi-threaded application, each thread can have the mask. Typically, the threads inherit the mask of the parent thread. When all the threads have blocked the signal, then the signal will remain pending until it is either unblocked or ignored. In a multi-threaded process, the signal will be delivered to the first thread found which is not blocking the signal.

Summarizing the above -

  • When a signal occurs, we say signal is generated
  • We define an action for required signals - signal disposition
  • When an action is taken for a signal, this means signal is delivered
  • If a signal is between generation and delivery, this means signal is pending
  • We can block a signal for a process. If the process doesn't ignore the blocked signal, the signalwill be pending
  • A blocked signal can be generated more than once before the process unblocks the signal. The kernel can deliver the signal once or more. If it delivers signals more than once, we say the signal is queued. If the signals are delivered only once, it is not queued
  • Each process (in single threaded application) or a thread (in a multi-threaded application) has a signal mask. Signal masks define blocked signals for a process or thread. It is just a bitarray which includes one bit for each signal. If the bit is on, that means related signal will be blocked
  • POSIX defines a data structure which holds one bit for each possible signal. This data structure isnamed signal set. It is an integer like data type. An integer is at least 32 bit value in 32 bitarchitectures. So we can hold status information for 32 different signals. We can define signalmask as a signal set. We can manage them by using some custom functions. POSIX defines somefunctions to modify any given signal set.
API for signal processing

Because of the history of Unix systems progression, there are a lot of APIs that help process signals. Broadly speaking, there are three major sets of API -
  • System V Systems Environment
  • BSD 4.3 Environment
  • POSIX environment
Unreliable Signals

This is the signal environment for the traditional System V systems. Some of the major limitations of this environment are -

  • Signal handlers are reset to SIG_DFL prior to being called - "one-shot" signal behavior
  • Recursive signal handling is always allowed
  • System calls interrupt when a signal is delivered
The above behavior cause the unreliable behavior.

These "one-shot'' signals must re-install the signal handler within the signal handler itself, if the program wishes the signal to remain installed. Because of this, there is a race condition in which the signal can arrive again before the handler is re-installed, which can cause the signal to either be lost or for the original behavior of the signal to be triggered (such as killing the process). Therefore, these signals are "unreliable'' because the signal catching and handler re-installation operations are nonatomic.

Under unreliable signal semantics, system calls are not restarted automatically when interrupted by a signal. Therefore, in order for a program to account for all cases, the program would need to check the value of errno after every system call, and reissue the system call if its value is EINTR.

Along similar lines, unreliable signal semantics don't provide an easy way to get an atomic pause operation (put the process to sleep until a signal arrives). Because of the unreliable nature of reinstalling signal handlers, there are cases in which a signal can arrive without the program realizing this.


int flag = 0;
main()
{
...
signal(SIGINT, handler);
...
while(flag == 0) {
pause();
}
...
}

handler()
{
signal(SIGINT, handler);
flag = 1;
}

In the above example, signals could be lost after entering the handler function, but before
the signal handler could be re-installed. Another race-condition would be when the flag is false and hence we enter the while-loop, but before we enter pause(), the signal occurs (Pause is used to wait for a signal to occur and returns as soon as a signal occurs). In this case the pause() misses the signal and potentially could wait forever if the signal does not occur again.

The interface to the traditional signal handling environment is:


int (*signal)(int signal_number, int (*function)(int));

Change the signal handler for the indicated signal. Signal_number indicates which signal, function is the new handler.


int pause(void);

Wait for a signal to arrive.

Two standard signal handlers exist:

  • SIG_DFL - Take the default action for this signal.
  • SIG_IGN - Ignore this signal.

BSD 4.x Signal Environment

In this environment, unreliability was removed by using the following enhancements -

  • Signals are blocked for the duration of a signal handler (i.e. recursive signals are not normally allowed)
  • A "signal mask" can be set to block most signals during critical regions
  • Signal handlers normally remain installed during and after signal delivery
  • A separate signal handler stack can be used if desired. Most system calls are restarted following delivery of a signal.
The interface here was still the old System V interface with the following additions -


int sigvec(int signal_number, struct sigvec *new_sigvec, struct sigvec *old_sigved);

Change or query signal handlers. Signal_number indicates which signal. New_sigvec defines the handler environment or may be null if you don't want to change the handler. If non-null, old_sigvec is filled with the current handler information.


int sigstack(char *stack);
Change the stack which will be used during signal delivery.

int siginterrupt(int signal_number, int interrupt);
Alter the SV_INTERRUPT property of a signal handler. If interrupt is zero, system calls will be restarted after signal delivery. If it is non-zero they will return EINTR.


int sigsetmask(int new_mask);

Change the set of masked/held signals. New_mask is a bit pattern describing the new set of signals. The old signal mask is returned.


int sigblock(int signal_mask);

Add a new set of signals to the current signal mask.


int sigpause(int signal_mask);

Wait for a signal using the given signal mask.

The sigvec structure defines the signal-handling semantics:


struct sigvec {
// signal handler
int (*sv_handler)(void);
// signals to mask during signal delivery
int sv_mask;
// signal delivery options
int sv_flags;
};

The sv_flags field describes the options you could use to alter signal handling. Standard options are:
SV_ONSTACK Use a special stack rather than the normal hardware stack. The stack to use must be specified using sigstack().
SV_RESETHAND Use V7-style "reset to default handler" signal handling semantics.
SV_INTERRUPT Allow system calls to be interrupted by signal delivery. Not all of these options are supported by "BSD-compatible" systems and

POSIX Environment


int sigaction(int signal_number, struct sigaction *new_handler, struct sigaction *old_handler);

Set or query the signal handling environment of a given signal.


int sigprocmask(int how, sigset_t *new_set, sigset_t *old_set);

Set or query the signal mask. If new_set is null, no change is made. If old_set is null, nothing is returned.


int sigemptyset(sigset_t *set);

Clear a signal mask.


int sigfillset(sigset_t *set);

Fill (add all possible signals to) a signal mask.


int sigaddset(sigset_t *set, int signal_number);

Add a signal to a signal mask.


int sigdelset(sigset_t *set, int signal_number);

Remove a signal from a signal mask


int sigismember(sigset_t *set, int signal_number);

See if a signal is a member of a signal mask.


int sigpending(sigset_t *set);

Return the set of signals that have been delivered but which were blocked.

The sigaction structure describes the signal handling environment:


struct sigaction {
void (*sa_handler)(int);
// new signal mask
sigset_t sa_mask;
// options
int sa_flags;
};

The same default signal handlers are used in POSIX as in V7.

Common options for sigaction() include:
SA_OLDSTYLE SA_RESETHAND V7 unreliable signal semantics.
SA_INTERRUPT Allow system calls to be interrupted by signal delivery.
SA_RESTART Allow system calls to be restarted after signal delivery.
SA_ONSTACK Use a special stack during signal handling.
SA_NOCLDSTOP Disable SIGCLD/SIGCHLD for stopped (versus terminated) processes. Only SA_NOCLDSTOP is required by the POSIX specification. Other options are often missing or have different names.

All Signals

SIGHUP 1 Exit Hangup
SIGINT 2 Exit Interrupt
SIGQUIT 3 Core Quit
SIGILL 4 Core Illegal Instruction
SIGTRAP 5 Core Trace/Breakpoint Trap
SIGABRT 6 Core Abort
SIGEMT 7 Core Emulation Trap
SIGFPE 8 Core Arithmetic Exception
SIGKILL 9 Exit Killed
SIGBUS 10 Core Bus Error
SIGSEGV 11 Core Segmentation Fault
SIGSYS 12 Core Bad System Call
SIGPIPE 13 Exit Broken Pipe
SIGALRM 14 Exit Alarm Clock
SIGTERM 15 Exit Terminated
SIGUSR1 16 Exit User Signal 1
SIGUSR2 17 Exit User Signal 2
SIGCHLD 18 Ignore Child Status
SIGPWR 19 Ignore Power Fail/Restart
SIGWINCH 20 Ignore Window Size Change
SIGURG 21 Ignore Urgent Socket Condition
SIGPOLL 22 Ignore Socket I/O Possible
SIGSTOP 23 Stop Stopped (signal)
SIGTSTP 24 Stop Stopped (user)
SIGCONT 25 Ignore Continued
SIGTTIN 26 Stop Stopped (tty input)
SIGTTOU 27 Stop Stopped (tty output)
SIGVTALRM 28 Exit Virtual Timer Expired
SIGPROF 29 Exit Profiling Timer Expired
SIGXCPU 30 Core CPU time limit exceeded
SIGXFSZ 31 Core File size limit exceeded
SIGWAITING 32 Ignore All LWPs blocked
SIGLWP 33 Ignore Virtual Interprocessor Interrupt for Threads Library
SIGAIO 34 Ignore Asynchronous I/O

1 Comments:

Anonymous Anonymous said...

В подобных случаях, преимущественно если совместная жизнь уже практически невозможна и даже опасна, желательно начало психологически подготовиться к некоему временному "шагу обратно", какой пользоваться чтобы разбега: примем, прежде встречать менее квалифицированную работу, для со временем восстановить прежние навыки (разве обрести новые) и дальше продолжить обеспечивать собственную финансовую независимость. Суть – научиться пользоваться обретенной свободой в собственных интересах. [url=http://profvesti.ru/o-stroitelstve-svoimi-rukami/79-stroitelstvo-basseyna-svoimi-rukami.html]ремонт квартир ключ[/url]

3:38 AM  

Post a Comment

<< Home