微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

中断被阻止的读取

我的程序经历了这样一个循环:

... while(1){ read(sockfd,buf,sizeof(buf)); ... }

读取function在等待input时阻塞,恰好来自套接字。 我想处理SIGINT,基本上告诉它如果正在读取,然后调用任意函数,则停止读取函数。 做这个的最好方式是什么?

在共享ARM9 GPIO中断(linux)上需要帮助处理多个共享I2C MAX3107芯片

Linux用户空间GPIO使用sysfs中断

多核处理器中基于轮询和中断的数据包处理方法

将两个数字卡连接到星号箱时的IRQ问题

Linux调度程序是否察觉到硬件中断(调度程序抖动)

从read(2) :

EINTR The call was interrupted by a signal before any data was read; see signal(7).

如果你修改你的代码看起来更像是:

cont = 1; while (1 && cont) { ret = read(sockfd,sizeof(buf)); if (ret < 0 && errno == EINTR) cont = arbitrary_function(); }

这使得arbitrary_function()决定read(2)是否应该重试。

更新

您需要处理信号以便从read(2)获得EINTR行为:

#include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<signal.h> #include<errno.h> int interrupted; void handle_int(num) { interrupted = 1; } int main(void){ char buf[9001]; struct sigaction int_handler = {.sa_handler=handle_int}; sigaction(SIGINT,&int_handler,0); while(!interrupted){ printf("interrupted: %dn",interrupted); if(read(0,sizeof(buf))<0){ if(errno==EINTR){ puts("eintr"); }else{ printf("%dn",errno); } puts("."); } } puts("end"); return 0; }

给出输出

$ ./foo interrupted: 0 hello interrupted: 0 ^Ceintr . end

当你的进程收到一个信号时, read()将返回, errno的值将被设置为EINTR 。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐