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

12 Comments:

Anonymous Anonymous said...

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

3:38 AM  
Blogger Taibai Li said...

huangqihang0603fitflops outlet
michael kors handbags
michael kors bags
kate spade uk
ralph lauren outlet
oakley sunglasses
michael kors outlet
chanel handbags
true religion outlet
chanel online shop
ray ban uk
christian louboutin outlet
burberry sale
abercrombie outlet
kate spade
fitflops sale clearance
gucci outlet online
michael kors
gucci uk
tory burch outlet online
ralph lauren
toms shoes
burberry outlet online
coach outlet online
oakley sunglass
ray ban outlet
nike air max
ray bans
ray ban sunglasses
michael kors outlet online
oakley sunglasses wholesale
chanel outlet
michael kors handbag
true religion
toms outlet
q

2:53 PM  
Blogger ninest123 Ninest said...

ninest123 10.27
tiffany jewelry, michael kors outlet, oakley sunglasses wholesale, ugg boots, louis vuitton, jordan shoes, nike air max, burberry outlet, uggs outlet, prada outlet, louis vuitton, ugg boots, louis vuitton outlet, michael kors outlet store, ray ban sunglasses, louis vuitton outlet, replica watches, replica watches, uggs outlet, michael kors outlet, polo ralph lauren outlet online, nike free, ray ban sunglasses, oakley sunglasses, christian louboutin outlet, michael kors outlet online, longchamp outlet, louis vuitton outlet, christian louboutin, tiffany and co, prada handbags, cheap oakley sunglasses, polo outlet, longchamp outlet, tory burch outlet, longchamp outlet, nike outlet, oakley sunglasses, oakley sunglasses, ray ban sunglasses, christian louboutin shoes, christian louboutin uk, chanel handbags, uggs on sale, burberry handbags, nike air max, kate spade outlet, michael kors outlet online

9:46 AM  
Blogger ninest123 Ninest said...

hollister uk, nike roshe run uk, sac longchamp pas cher, nike air max uk, north face, vans pas cher, michael kors, kate spade, nike blazer pas cher, longchamp pas cher, ray ban uk, nike free run, abercrombie and fitch uk, louboutin pas cher, coach outlet store online, timberland pas cher, nike roshe, north face uk, polo ralph lauren, oakley pas cher, nike air max, sac vanessa bruno, hollister pas cher, polo lacoste, true religion outlet, ralph lauren uk, nike tn, sac hermes, ray ban pas cher, coach outlet, jordan pas cher, michael kors, coach purses, nike air force, true religion jeans, lululemon canada, michael kors pas cher, mulberry uk, nike air max uk, true religion outlet, burberry pas cher, michael kors outlet, nike free uk, converse pas cher, coach outlet, hogan outlet, new balance, guess pas cher, true religion outlet, air max

9:47 AM  
Blogger ninest123 Ninest said...

bottega veneta, new balance shoes, nike air max, soccer jerseys, louboutin, giuseppe zanotti outlet, lululemon, mac cosmetics, vans, nike trainers uk, vans outlet, abercrombie and fitch, reebok outlet, nike air max, converse, iphone 6 cases, insanity workout, ghd hair, hollister clothing, converse outlet, oakley, nfl jerseys, baseball bats, herve leger, gucci, nike huaraches, mont blanc pens, north face outlet, ferragamo shoes, valentino shoes, north face outlet, p90x workout, longchamp uk, nike roshe run, soccer shoes, wedding dresses, timberland boots, hollister, hermes belt, hollister, ralph lauren, jimmy choo outlet, chi flat iron, asics running shoes, ray ban, instyler, mcm handbags, beats by dre, celine handbags, babyliss, gucci handbags, michael kors outlet online

9:48 AM  
Blogger ninest123 Ninest said...

toms shoes, ugg, ugg uk, moncler, moncler, juicy couture outlet, hollister, ugg,uggs,uggs canada, michael kors outlet online, canada goose outlet, lancel, wedding dresses, moncler outlet, canada goose, swarovski, barbour uk, moncler, canada goose outlet, louis vuitton, ugg,ugg australia,ugg italia, louis vuitton, moncler uk, louis vuitton, ugg pas cher, louis vuitton, montre pas cher, links of london, marc jacobs, barbour, louis vuitton, canada goose uk, michael kors handbags, canada goose outlet, pandora charms, supra shoes, replica watches, canada goose, juicy couture outlet, coach outlet, karen millen uk, moncler outlet, moncler, pandora uk, doudoune moncler, thomas sabo, swarovski crystal, pandora jewelry, canada goose jackets, michael kors outlet, canada goose, doke gabbana, pandora jewelry
ninest123 10.27

9:49 AM  
Blogger oakleyses said...

christian louboutin uk, louis vuitton outlet, christian louboutin shoes, michael kors pas cher, louis vuitton outlet, sac longchamp pas cher, prada handbags, gucci handbags, tiffany and co, polo ralph lauren outlet online, christian louboutin outlet, cheap oakley sunglasses, longchamp outlet, uggs on sale, polo outlet, louis vuitton, nike air max, oakley sunglasses, longchamp outlet, nike free, nike outlet, longchamp outlet, longchamp pas cher, chanel handbags, nike air max, oakley sunglasses, nike free run, tiffany jewelry, oakley sunglasses wholesale, louboutin pas cher, ray ban sunglasses, ugg boots, replica watches, air max, louis vuitton outlet, oakley sunglasses, nike roshe, louis vuitton, tory burch outlet, ray ban sunglasses, jordan shoes, christian louboutin, prada outlet, polo ralph lauren, burberry pas cher, ugg boots, jordan pas cher, kate spade outlet, ray ban sunglasses

8:39 AM  
Blogger oakleyses said...

nike blazer pas cher, mulberry uk, burberry handbags, michael kors, timberland pas cher, oakley pas cher, ray ban uk, vans pas cher, coach purses, north face, nike free uk, new balance, ray ban pas cher, sac hermes, michael kors, nike air force, ralph lauren uk, nike air max, kate spade, nike roshe run uk, true religion jeans, north face uk, hogan outlet, michael kors outlet online, nike air max uk, uggs outlet, nike tn, burberry outlet, hollister uk, coach outlet store online, replica handbags, lululemon canada, michael kors outlet online, michael kors outlet online, michael kors outlet, michael kors outlet online, converse pas cher, michael kors outlet, true religion outlet, true religion outlet, polo lacoste, hollister pas cher, coach outlet, guess pas cher, true religion outlet, abercrombie and fitch uk, nike air max uk, sac vanessa bruno, michael kors outlet

8:41 AM  
Blogger oakleyses said...

hollister, oakley, celine handbags, instyler, nike trainers uk, ghd hair, converse outlet, hollister clothing, hermes belt, beats by dre, ray ban, lancel, herve leger, timberland boots, nike air max, chi flat iron, longchamp uk, asics running shoes, vans, nike air max, insanity workout, reebok outlet, giuseppe zanotti outlet, abercrombie and fitch, nike roshe run, north face outlet, louboutin, jimmy choo outlet, iphone cases, gucci, mcm handbags, north face outlet, valentino shoes, soccer shoes, hollister, wedding dresses, babyliss, bottega veneta, baseball bats, p90x workout, nfl jerseys, nike huaraches, new balance shoes, soccer jerseys, mont blanc pens, ralph lauren, vans outlet, mac cosmetics, ferragamo shoes, lululemon

8:44 AM  
Blogger oakleyses said...

hollister, louis vuitton, moncler outlet, pandora uk, moncler, canada goose outlet, ugg,ugg australia,ugg italia, marc jacobs, toms shoes, moncler outlet, louis vuitton, canada goose, swarovski crystal, supra shoes, moncler, ugg, juicy couture outlet, wedding dresses, thomas sabo, karen millen uk, ugg pas cher, canada goose jackets, pandora jewelry, louis vuitton, moncler, swarovski, pandora jewelry, links of london, moncler uk, louis vuitton, coach outlet, ugg uk, canada goose uk, ugg,uggs,uggs canada, canada goose, doudoune moncler, louis vuitton, pandora charms, juicy couture outlet, canada goose outlet, canada goose outlet, canada goose, moncler, replica watches, montre pas cher

8:47 AM  
Blogger Liu Liu said...

Nick Saban’s relatively brief time as head coach of the Miami Dolphins is not looked upon fondly by most fans of the team. He went 15-17 christian louboutin shoes in his two seasons, but basically quit on the nfl jerseys store team in the final weeks Nike Air Max 90 of the 2006 season, focused more on his next job, at the University of Alabama, instead of the one he christian louboutin uk was under contract for.And at least one player who played – or at Christian Louboutin Women Flat least practiced – under Saban during those ill-fated christian louboutin men flat final weeks Nike Roshe Run hasn’t forgotten NFL Jerseys how Nike Free Run he was louboutin outlet treated. According to Nike Air Max 2015 Shoes receiver P.K. Sam, a journeyman cheap nfl jerseys who spent time with five NFL teams as well as two CFL clubs, Saban cut wholesale nfl jerseys him after he left the team christian louboutin Panettone spiked leather wallet briefly to see his dying father

2:53 PM  
Anonymous Obat Sariawan Alami said...

This information is very useful. thank you for sharing. and I will also share information about health through the website

Obat Sakit Mata Belekan Alami
Cara Mengatasi Diare
Obat Penghancur Batu ginjal
Cara Menghilangkan Varises
Obat Sakit perut melilit paling Ampuh
Cara Mudah Menghilangkan Keloid

3:53 PM  

Post a Comment

<< Home