zony.me

EINTR-信号中断与慢系统调用

什么是慢系统调用?

慢系统调用指的是那些可能永远阻塞的系统调用,永远阻塞的系统调用意味着该调用永远无法返回,而多数网络支持函数都属于这一类系统调用。就如同**accept()**函数,如果没有客户连接,那么该调用将会一直阻塞。

EINTR介绍

早期的Unix系统,如果进程在一个慢系统调用(slow system call)中阻塞时,当捕获到某个信号且相应信号处理函数返回时,这个系统调用被中断,调用返回错误,设置errno为EINTR(相应的错误描述为“Interrupted system call”)。

不同函数产生EINTR错误,所代表的含义也不尽相同。

系统调用函数 errno为EINTR表征的意义
write 由于信号中断,没有成功任何数据。
open 由于信号中断,没有读到任何数据。
recv 由于信号中断返回,没有任何数据可用。
sem_wait 函数调用被信号处理函数终端。

如何处理被中断的系统调用

既然系统调用会被中断,那么别忘了要处理被中断的系统调用。有三种处理方式:

C
again:  
          if ((n = read(fd, buf, BUFFSIZE)) < 0) {  
             if (errno == EINTR)  
                  goto again;     /* just an interrupted system call */  
            /* handle other errors */  
          }  
……
 
while ((r = read (fd, buf, len)) < 0 && errno == EINTR) /*do
nothing*/ ;
 
……
ssize_t Read(int fd, void *ptr, size_t nbytes)
{
 
        ssize_t n;
 
again:
        if((n = read(fd, ptr, nbytes)) == -1){
                if(errno == EINTR)
                        goto again;
                else
                        return -1;
        }
        return n;
}
C
struct sigaction action;
 
action.sa_handler = handler_func;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
/* 设置SA_RESTART属性 */
action.sa_flags |= SA_RESTART;
 
sigaction(SIGALRM, &action, NULL);

但注意,并不是所有的系统调用都可以自动恢复。如msgsnd喝msgrcv就是典型的例子,msgsnd/msgrcv以block方式发送/接收消息时,会因为进程收到了信号而中断。此时msgsnd/msgrcv将返回-1,errno被设置为EINTR。且即使在插入信号时设置了SA_RESTART,也无效。在man msgrcv中就有提到这点:

msgsnd and msgrcv are never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.

C
struct sigaction action;
 
action.sa_handler = SIG_IGN;
sigemptyset(&action.sa_mask);
 
sigaction(SIGALRM, &action, NULL);

文章转载自:http://blog.csdn.net/benkaoya/article/details/17262053

EINTR-信号中断与慢系统调用
作者 Zony · 发布于 2016-07-22
Licensed under CC BY-NC-SA 4.0
← 上一篇C# Collection 与 Collection下一篇 →ASP.Net MVC4学习 - 初学MVC控制器
目录