select调用
来源:互联网 发布:笛子软件 编辑:程序博客网 时间:2024/06/06 02:32
标签(空格分隔): Linux C/C++
select 调用
1. 函数调用原型
int select(int maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,const struct timeval *timeout)
2.参数说明
2.1 timeout参数
结构体定义:
struct timeval { long tv_sec;//秒 long tv_usec;//微秒};
如果这个参数不为null,且为有效的一段时间(不为0)那么select会在等待这个时间内,返回,不管有没有这三种事件发生。
如果为null,那么select调用会阻塞下去,直到readset,writeset,exceptset中的对应的文件描述符上有对应的事件发生。
如果这个值不为null但是里面的值为0(tv_sec=tv_usec=0),那么这个调用,会检查有没有文件描述符可以使用(对应的可读,可写,异常),然后立即返回。
这个也叫做polling。
2.2 readset,writeset,exceptset
这三个参数分别是调用者,感兴趣文件描述符的集合,select会监控这三个集合中的文件描述符的状态,然后根据发生的事件返回,返回会调用者需要检测是read,write,except哪一种事件发生了。
下面提供了对于文件描述符集合的几个函数(实际为宏定义)
- 从集合当中删除描述符fd
void FD_CLR(int fd,fd_set *set)
- 将fd描述符添加到集合当中
void FD_SET(int fd,fd_set * set)
- 将集合中设置监控的文件描述符清空
void FD_ZERO(fd_set * set)
- 判断fd是不是在集合当中
int FD_ISSET(int fd,fd_set* set)
2.3 maxfdp1
监听文件描述符数值的最大值+1
2.4 返回值
- 有监控的事件发生返回发生的事件的个数
- 超时返回或者出错-1
3.使用方法
下面是一个类似可以响应多个客户端连接的服务器程序。
#include <stdio.h>#include <stdlib.h>#include <unistd.h>int main(int argc,char* argv[]){ fd_set rfds; struct timeval tv; int retval; int listenedfd; FD_ZERO(&rfds);/*初始化集合*/ /*添加监控的文件描述符到集合当中*/ FD_SET(listenefd, &rfds); /*Wait up to five seconds. 设置超时时间 */ tv.tv_sec = 5; tv.tv_usec = 0; /*调用select 在超时时间tv内返回*/ retval = select(listenefd + 1, &rfds, NULL, NULL, &tv); /* Don't rely on the value of tv now! */ if (retval == -1)/*超时或者出错*/ perror("select()"); else if (retval){ /*有返回,监控的文件描述符会有相应的事件*/ printf("Data is available now.\n"); /**接受连接,并保存在RIOfd(感兴趣的fd)数组中,以便后来处理*/ if(FD_ISSET(listenfd, &rfds)){ /*接受连接*/ accept_connection(); /*保存连接*/ save_connected_fd(); } } /* FD_ISSET(0, &rfds) will be true. */ /*遍历所有的感兴趣的文件描述符,是否发生了事件*/ for(int i=0;i<maxRIOfdnumber;++i){ if(FD_ISSET(RIOfd[i], &rfds)) /*对发生的事件进行处理*/ do_with(RIOfd[i]); }else printf("No data within five seconds.\n"); } exit(EXIT_SUCCESS);}
4.参考内容
- Linux man select
- Unix 网络编程 卷I 套接字联网API
0 0
- select调用
- select系统调用
- 关于select系统调用
- select系统调用
- select系统调用
- select系统调用
- linux Select()系统调用
- linux系统调用select
- Select系统调用方法
- Linux select系统调用
- linux select 系统调用
- linux select 系统调用
- select系统调用
- linux下select系统调用
- select操作的函数调用
- linux程序设计SELECT系统调用
- JS函数select()无法调用
- 调用和修改 select 样式,
- bzoj 1552: [Cerc2007]robotic sort(splay)
- <canvas>学习笔记——如何使用<canvas>
- chmod命令
- hdu 4706 Children's Day
- LeetCode|Range Sum Query - Immutable
- select调用
- 控件listbox的使用
- HDUOJ-1010 Tempter of the Bone(深搜+剪枝优化)
- hdu 4707 Pet
- eclipse下如何打开ftl文件
- Java相关错误
- 小算法:给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串s首先
- Javascript中事件捕获、事件冒泡以及事件委托机制
- 1.1你是谁?你从哪来?你到哪去? -交给学习来解答