c - 中断阻塞读

标签 c linux signals interrupt

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

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

read 函数在等待输入时阻塞,而输入恰好来自套接字。我想处理 SIGINT 并基本上告诉它在读取时停止读取函数,然后调用任意函数。执行此操作的最佳方法是什么?

最佳答案

来自 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, buf, 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(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: %d\n", interrupted);
    if(read(0,buf,sizeof(buf))<0){
      if(errno==EINTR){
        puts("eintr");
      }else{
        printf("%d\n",errno);
      }
      puts(".");
    }
  }
  puts("end");
  return 0;
}

给出输出:

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

关于c - 中断阻塞读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6249577/

相关文章:

linux - 在目录中查找文件,使用 execdir 执行命令并重定向

java - sun.misc.Signal 的替代品

bash - 使用 bash 通过 ssh 启动一个进程,然后在 sigint 上终止它

将 IP 地址与 C 编程进行比较

c - 对于 10 个整数的数组,表达式 arr 和 &arr 是否相同?

用级数计算 pi

linux - gnu screen 不要改变我的窗口标题

c - 我的 C 版 helloworld 正在编译,但 .exe 文件没有运行?

linux - Kernel Source -- 在哪个文件中定义了 brk()

c++ - 不建议通过 Qt Signals 发出大量数据