Advanced Programming in UNIX Environment Episode 41

#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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值