Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 10.10 alarmandpauseFunctions 343


Here, we specifically want a slow system call to be interrupted. We’ll see a portable
way to do this in Section 10.14.

Example


Let’s redo the preceding example usinglongjmp.This way, we don’t need to worry
about whether a slow system call is interrupted.
#include "apue.h"
#include <setjmp.h>

static void sig_alrm(int);
static jmp_buf env_alrm;

int
main(void)
{
int n;
char line[MAXLINE];

if (signal(SIGALRM, sig_alrm) == SIG_ERR)
err_sys("signal(SIGALRM) error");
if (setjmp(env_alrm) != 0)
err_quit("read timeout");

alarm(10);
if ((n = read(STDIN_FILENO, line, MAXLINE)) < 0)
err_sys("read error");
alarm(0);

write(STDOUT_FILENO, line, n);
exit(0);
}

static void
sig_alrm(int signo)
{
longjmp(env_alrm, 1);
}

Figure 10.11 Callingreadwith a timeout, usinglongjmp

This version works as expected, regardless of whether the system restarts interrupted
system calls. Realize, however,that we still have the problem of interactions with other
signal handlers, as in Figure10.8.

If we want to set a time limit on an I/O operation, we need to uselongjmp,as
shown previously,while recognizing its possible interaction with other signal handlers.
Another option is to use theselectorpollfunctions, described in Sections 14.4.1 and
14.4.2.
Free download pdf