与信号的关系缓慢的系统调用 [英] Relationship slow system call with signal

查看:33
本文介绍了与信号的关系缓慢的系统调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习缓慢的系统调用和信号.
对于普通系统来说,缓慢的系统调用(从终端设备读取)可以永远阻塞.
和下面的例子,可以在一段时间后读取超时.

I'm learning slow system call and signals.
For the normal system, the slow system call (read from terminal device) can block forever.
and below example, it is possible to read to time out after some amount of time.

但是当我执行它时,超时没有任何作用.
我不明白为什么.
你能解释一下并向我展示另一个缓慢系统调用的例子吗?

But when I excuted it, The time out does nothing.
I can't understand why.
Could you explain and show me another example of slow system call?

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

static void sig_alrm(int signo){

}

int main(){
    int n;
    char line[50];

    if(signal(SIGALRM, sig_alrm) == SIG_ERR)
        printf("signal(SIGALRM) error");

    alarm(1);
    if((n = read(STDIN_FILENO, line, 50)) < 0)
        printf("read error");
    alarm(0);

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

推荐答案

您的处理程序在一秒钟后被调用.如果你检查你会看到它被调用.我不建议放置 printf 因为它不是异步信号安全的,所以你可以让它设置一个变量或其他东西.

Your handler gets called after a second. If you check you will see it gets called. I don't recommend putting a printf since it's not async-signal-safe, put you can make it set a variable or something.

无论如何,回到问题.如果您想知道为什么 read 不会因 EINTR 而失败,那么答案是 SA_RESTART.在大多数 Unix 系统上,一些系统调用会在出现信号时自动重新启动.

Anyway, back to the question. If you're wondering why the read doesn't fail with EINTR the answer is SA_RESTART. On most Unix systems a few system calls are automatically restarted in the event of a signal.

列表不是标准的,但是 IIRC read(v), write(v) 和朋友是经常重启的一部分.

The list is not standard but IIRC read(v), write(v) and friends are part of the ones commonly restarted.

这篇关于与信号的关系缓慢的系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆