我的程序经历了这样的循环:
...
while(1){
read(sockfd,buf,sizeof(buf));
...
}
read函数在等待输入时阻塞,这恰好来自套接字。我想处理SIGINT并且基本上告诉它在读取时停止读取函数然后调用任意函数。这样做的最佳方式是什么?
答案 0 :(得分:15)
来自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)
。
<强>更新强>
您需要处理信号才能从EINTR
获取read(2)
行为:
#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: %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
答案 1 :(得分:2)
当您的流程收到信号时,read()
将返回,errno
的值将设置为EINTR
。