#include "apue.h"
unsigned int sleep2(unsigned int);
static void sig_int(int);
int main(void)
{
unsigned int unslept;
if(signal(SIGINT,sig_int)==SIG_ERR)
err_sys("signal(SIGINT) error");
unslept=sleep2(5);
printf("sleep2 returned: %u\n",unslept);
return 0;
}
static void sign_int (int signo)
{
int i,j;
volatile int k;
printf("\nsig_int starting\n");
for(i=0;i<300000;i++)
for(j=0;j<4000;j++)
k+=i*j;
printf("sig_int finished\n");
}
Calling sleep2 from a program that catches other signals
#include "apue.h"
static void sig_alrm(int);
int main(void)
{
int n;
char line[MAXLINE];
if(signal(SIGALRM,sig_alrm)==SIG_ERR)
err_sys("signal(SIGALRM) error");
alarm(10);
if((n=read(STDIN_FILENO,line,MAXLINE))<0)
err_sys("read error");
alarm(0);
write(STDOUT_FILENO,line,n);
return 0;
}
static void sig_alrm(int signo)
{
}
Calling read with a timeout
This sequence of code is common in UNIX applications, but this program has two problems.
1.The program in Figure 10.10 has one of the same flaws that we described in Figure 10.7: a race condition between the first call to alarm and the call to read. If the kernel blocks the process between these two function calls for longer than the alarm period, the read could block forever. Most operations of this type use a long alarm period, such as a minute or more, making this unlikely; nevertheless, it is a race condition.
2.If system calls are automatically restarted, the read is not interrupted when the SIGALRM signal handler returns. In this case, the timeout does nothing.
#include "apue.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);
return 0;
}
static void sig_alrm(int signo)
{
longjmp(env_alrm,1);
}
Calling read with a timeout, using longjmp
This version works as expected, regardless of whether the system restarts interrupted system calls.