Relationship slow system call with signal

被刻印的时光 ゝ 提交于 2020-02-25 01:42:08

问题


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);
}    

回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/6226305/relationship-slow-system-call-with-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!