中断阻塞读取
发布时间:2020-12-16 02:59:53 所属栏目:百科 来源:网络整理
导读:我的程序通过这样的循环: ...while(1){ read(sockfd,buf,sizeof(buf)); ...} 读取功能在等待输入时阻塞,恰好来自插座.我想处理SIGINT,并且基本上告诉它停止读取功能,如果它正在读取,然后调用任意函数.这样做最好的方法是什么? 解决方法 从阅读(2): EINTR
我的程序通过这样的循环:
... while(1){ read(sockfd,buf,sizeof(buf)); ... } 读取功能在等待输入时阻塞,恰好来自插座.我想处理SIGINT,并且基本上告诉它停止读取功能,如果它正在读取,然后调用任意函数.这样做最好的方法是什么? 解决方法
从阅读(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(); } 这使得____()决定是否重新尝试读取(2). 更新 您需要处理信号才能从读取(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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |