Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 5: Locking and Interprocess Communication


ImplementingSignalHandlers


Thesigactionsystem call is used to install a new handler function.

#include<signal.h>
#include<stdio.h>

/* Handler function */
void handler(int sig) {
printf("Receive signal: %u\n", sig);
};

int main(void) {
struct sigaction sa;
int count;

/* Initialize the signal handler structure */
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;

/* Assign a new handler function to the SIGTERM signal */
sigaction(SIGTERM, &sa, NULL);

sigprocmask(&sa.sa_mask); /* Accept all signals */
/* Block and wait until a signal arrives */
while (1) {
sigsuspend(&sa.sa_mask);
printf("loop\n");
}

return 0;
};

If no user-specific handler function is assigned to a signal, the kernel automatically installs predefined
functions to provide reasonable standard operations and to deal with the specific situation.

The definition of the field of typesigactionused to describe the new handler is platform-specific but
has practically the same contents on all architectures.

<asm-arch/signal.h>
struct sigaction {
__sighandler_t sa_handler;
unsigned long sa_flags;
...
sigset_t sa_mask; /* mask last for extensibility */
};

❑ sa_handleris a pointer to the handler function invoked by the kernel when a signal arrives.
❑ sa_maskcontains a bitmask with exactly one bit for each signal available in the system. It is used
to block other signals during execution of the handler routine. On completion of the routine, the
kernel resets the list of blocked signals to its value prior to signal handling.
❑ sa_flagscontains additional flags to specify how the signal must be handled; these are docu-
mented in various system programming manuals.
Free download pdf