Linux被中断的系统调用详解与EINTR处理
前言
所谓慢系统调用,是指那些可能因等待外部事件而永久阻塞、导致进程无法返回的系统调用。例如,在没有客户端连接时调用accept,或在没有输入数据时调用read,均属于此类慢速操作。
在Linux环境下,如果进程正阻塞于某个慢系统调用期间捕获到一个信号,内核会中断该调用并转去执行信号处理函数,这种现象被称为被中断的系统调用。
然而,当信号处理函数执行完毕返回后,根据注册方式的不同,可能会面临以下几种不同的后续情况:
- 若信号处理函数是通过signal函数注册的,内核会自动重启该被中断的系统调用,因此原函数不会立即返回给用户空间。
- 如果信号处理函数是用sigaction注册的
- 在默认配置下,系统调用不会自动重启,此时函数将向用户返回失败状态,并将全局变量errno设置为EINTR以指示中断原因。
- 仅当通过sigaction注册信号且设置了SA_RESTART标志时,被中断的系统调用才会像未中断一样自动继续执行并重启。
接下来我们将编写具体的测试代码,分别验证上述三种情形。测试中选用的系统调用为read,用于产生中断的信号为SIGALRM,该信号由alarm定时器触发。
使用signal
#include
#include
#include
#include
void handler(int s)
{
printf("read is interrupt by signal handler\n");
return;
}
int main()
{
char buf[10];
int nread = 0;
signal(SIGALRM, handler);
alarm(2);
printf("read start\n");
nread = read(STDIN_FILENO, buf, sizeof(buf));
printf("read return\n");
if ((nread < 0) && (errno == EINTR))
{
printf("read return failed, errno is EINTR\n");
}
return 0;
}

使用sigaction + 默认情况
#include
#include
#include
#include
void handler(int s)
{
printf("read is interrupt by signal handler\n");
return;
}
int main()
{
char buf[10];
int nread = 0;
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_handler = handler;
act.sa_flags = 0; //不给SIGALRM信号设置SA_RESTART标志,使用sigaction的默认处理方式
//act.sa_flag |= SA_INTERRUPT; //SA_INTERRUPT是sigaction的默认处理方式,即不自动重启被中断的系统调用
//实际上,不管act.sa_flags值为多少,只要不设置SA_RESTART,sigaction都是按SA_INTERRUPT处理的
sigaction(SIGALRM, &act, NULL);
alarm(2);
printf("read start\n");
nread = read(STDIN_FILENO, buf, sizeof(buf));
printf("read return\n");
if ((nread < 0) && (errno == EINTR))
{
printf("read return failed, errno is EINTR\n");
}
return 0;
}

使用sigaction + 指定SA_RESTART标志
#include
#include
#include
#include
void handler(int s)
{
printf("read is interrupt by signal handler\n");
return;
}
int main()
{
char buf[10];
int nread = 0;
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_handler = handler;
act.sa_flags = 0;
act.sa_flags |= SA_RESTART; //给SIGALRM信号设置SA_RESTART标志
sigaction(SIGALRM, &act, NULL);
alarm(2);
printf("read start\n");
nread = read(STDIN_FILENO, buf, sizeof(buf));
printf("read return\n");
if ((nread < 0) && (errno == EINTR))
{
printf("read return failed, errno is EINTR\n");
}
return 0;
}

由于不同机制对被中断系统调用的处理方式存在显著差异,这对应用程序开发带来了以下挑战:
- 应用程序通常无法确切知晓底层使用的信号处理函数注册方式,也无法确定是否显式设置了SA_RESTART标志。
- 为了保证代码的可移植性,必须对关键函数的出错返回进行显式处理。当函数返回错误且errno等于EINTR时,应根据具体业务需求决定是忽略该错误还是重启该函数调用。
int nread = read(fd, buf, 1024);
if (nread < 0)
{
if (errno == EINTR)
{
//read被中断,其实不应该算作失败,可以根据实际需求进行处理,比如重写调用read,也可以忽略它
}
else
{
//read真正的读错误
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。