Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 13: System Calls


the kernel once the signal handler has terminated. Because this behavior is transparent to the user
application and also dispenses with repeated implementation of checks for the-EINTRreturn value
and call restarting, this alternative is much more popular with programmers than the System V
approach.


Linux supports the BSD variant by means of theSA_RESTARTflag, which can be specified on a per-signal
basis when handler routines are installed (see Chapter 5). The mechanism proposed by System V is
used by default because the BSD mechanism also occasionally gives rise to difficulties, as the following
example taken from [ME02], page 229, shows.


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

volatile int signaled = 0;

void handler (int signum) {
printf("signaled called\n");
signaled = 1;
}

int main() {
char ch;
struct sigaction sigact;
sigact.sa_handler = handler;
sigact.sa_flags = SA_RESTART;
sigaction(SIGINT, &sigact, NULL);

while (read(STDIN_FILENO, &ch, 1) != 1 && !signaled);
}

This short C program waits in awhileloop until the user enters a character via standard input or until
the program is interrupted by theSIGINTsignal (which can be sent usingkill -INTor by pressing
CTRL-C). Let us examine the code flow. If the user hits a normal key that does not causeSIGINTto be
sent,readyields a positive return code, namely, the number of characters read.


The argument of thewhileloop must return a logically false value to terminate execution. This happens
if one of the two logical queries linked by&&(and) is false — which is the case when


❑ A single key was pressed;readthen returns 1 and the test to check that the return value is not
equal to 1 returns a logically false value.
❑ Thesignaledvariable is set to 1 because the negation of the variable (!signaled)alsoreturnsa
logically false value.

These conditions simply mean that the program waits either for keyboard input or the arrival of the
SIGINT signal in order to terminate.


To apply System V behavior for the code as implemented by default under Linux, it is necessary to sup-
press setting of theSA_RESTARTflag; in other words, the linesigact.sa_flags = SA_RESTARTmust be
deleted or commented out. Once this has been done, the program runs as described and can be termi-
nated either by pressing a key or sendingSIGINT.

Free download pdf