Signals, Part 2: POSIX Signals

By Danny Kalev, ITworld |  How-to

The POSIX signal implementation ensures that if a process is already
handling a signal, other incoming signals are suspended until the
handler returns. However, if a signal SIGx is sent while a SIGx signal
is already pending, the kernel delivers only one SIGx signal to the
process. This isn't much of a problem since signals don't carry any
information other than the signal number itself. Thus, sending a signal
multiple times in very short periods is similar to sending it once.

Signal Sets
The POSIX signal functions (declared in ) operate on sets of
signals packed in a sigset_t datatype. Here are their prototypes and
descriptions:

* int sigemptyset(sigset_t * pset); -- Clears all the signals in
pset.
* int sigfillset(sigset_t * pset); -- Fills pset with all available
signals.
* int sigaddset(sigset_t * pset, int signum); -- Adds signal signum
to pset.
* int sigdelset(sigset_t * pset, int signum); -- Removes signal
signum from pset.
* int sigismember(const sigset_t * pset, int signum); -- Returns a
nonzero value if signum is included in pset, 0 otherwise.

Registering a Handler
To register a handler, call sigaction():

int sigaction(int signum, struct sigaction * act, struct sigaction *
prev);

sigaction() sets a handler for signal signum. The kernel's handling of
signum is described in the argument act, which is of type sigaction:

struct sigaction {
sighanlder_t sa_hanlder;
sigset_t sa_mask;
unsigned long sa_flags;
void (*sa_restorer)(void); /*never used*/
};

sa_hanlder is a pointer to a function of the type:

void handler (int signum);

However, it can also take one of two special values: SIG_DFL and
SIG_IGN. The sa_mask field contains all the signals that the kernel
should block while the handler is running. Note that the signal being
handled is always blocked, regardless of sa_mask's value. You can
override this behavior by setting the appropriate flags of the sa_flags
field. These flags can take one or more of the following values
combined by the bitwise OR operator:

* SA_NOCLDSTOP -- Ensures a parent doesn't receive a SIGCHLD signal
if one of its children is stopped.
* SA_NOMASK -- Overrides the default blocking of the signal if its
handler is currently executing. This flag enables you to emulate
ANSI's unreliable signals.
* SA_ONESHOT -- Resets the handler of signum to SIG_DFL. This flag
emulates the behavior of the ANSI signal() function
* SA_RESTART -- Ensures that a syscall restarts when the handler
exits.

If sigactions's final argument isn't NULL, it is filled with the
disposition of signum before sigaction() was called. To obtain the
current signal disposition without altering it, pass NULL as a second
argument and a valid sigaction pointer as the third.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question