本文介绍了中断阻塞读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程序经过这样的循环:
My program goes through a loop like this:
...
while(1){
read(sockfd,buf,sizeof(buf));
...
}
读功能块时,它等待输入,这恰好是从一个插座。我想处理SIGINT,基本上告诉它,如果它是读书停止读取功能,然后调用任意函数。什么是做到这一点的最好方法是什么?
The read function blocks when it is waiting for input, which happens to be from a socket. I want to handle SIGINT and basically tell it to stop the read function if it is reading and then call an arbitrary function. What is the best way to do this?
推荐答案
从阅读(2)
:
EINTR The call was interrupted by a signal before any data
was read; see signal(7).
如果你修改你的code看起来更像是:
If you amend your code to look more like:
cont = 1;
while (1 && cont) {
ret = read(sockfd, buf, sizeof(buf));
if (ret < 0 && errno == EINTR)
cont = arbitrary_function();
}
这让 arbitrary_function()
决定是否阅读(2)
应重新审理或者不。
This lets arbitrary_function()
decide if the read(2)
should be re-tried or not.
更新
您需要,以获得从的
来处理信号: EINTR
行为读取(2)
You need to handle the signal in order to get the EINTR
behavior from 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
这篇关于中断阻塞读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!