select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing

【版权申明】转载请附上出处链接 

select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing

/* According to POSIX.1-2001, POSIX.1-2008 */
#include <sys/select.h>

/* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
       fd_set *exceptfds, struct timeval *timeout);

void FD_CLR(int fd, fd_set *set);
int  FD_ISSET(int fd, fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);

#include <sys/select.h>

int pselect(int nfds, fd_set *readfds, fd_set *writefds,
        fd_set *exceptfds, const struct timespec *timeout,
        const sigset_t *sigmask);

Four macros are provided to manipulate the sets.

  • FD_ZERO() clears a set.
  • FD_SET() and FD_CLR() respectively add and remove a given file descriptor
    from a set.
  • FD_ISSET() tests to see if a file descriptor is part of the set; this is useful after select() returns.

select()

select系统调用。
在指定的时间内,监听用户指定的文件描述符上的可读、可写和异常等事件。
select()使用一种有序的方式,对多个套接字进行统一管理(监视与上报) 。

/**
 * @function 将监视每个fds集合中指示的文件描述符
 * 
 * @param nfds		应设置为三个fds(readfds/writefds/exceptfds)中编号最高的文件描述符加上1
 * @param readfds/writefds/exceptfds	分别指向可读、可写和异常等事件对应的描述符集合
 * @param timeout	设置select函数的超时时间,即告诉内核select等待多长时间之后就放弃等待。timeout == NULL 表示等待无限长的时间
 * 
 * @return	如果成功,select()和pselect()将返回三个返回的描述符集中包含的文件描述符的数量(即,readfd、writefds、exctfd中设置的总位数)
	如果在发生任何有趣的事情之前超时到期,则该值可能为零。
	出错时,返回-1,并设置errno以指示错误。
 */
int select(int nfds, fd_set *readfds, fd_set *writefds,
                  fd_set *exceptfds, struct timeval *timeout);
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
	fd_set fds;
	struct timeval tv;
	int ret;
	
	FD_ZERO(&fds);
	FD_SET(0,&fds);
	
	tv.tv_sec = 5;
	tv.tv_usec = 0;
	ret = select(1,&fds,NULL,NULL,&tv);
	
	if(ret == 0) //超时
	{
		printf("select() time out!\n");
	}
	else if(ret == -1)  //失败
	{
		printf("failed to select()!\n");
	}
	else  //成功
	{
		printf("select() success!\n");
	}

	return 0;
}

fd_set类型:

/* The fd_set member is required to be an array of longs.  */
typedef long int __fd_mask;

#define __NFDBITS       (8 * (int) sizeof (__fd_mask))
#define __FD_SETSIZE                1024

/* fd_set for select and pselect. */
typedef struct
{
    /* XPG4.2 requires this member name.  Otherwise avoid the name
       from the global namespace.  */
#ifdef __USE_XOPEN
    __fd_mask fds_bits[__FD_SETSIZE / __NFDBITS];
	#define __FDS_BITS(set) ((set)->fds_bits)
#else
    __fd_mask __fds_bits[__FD_SETSIZE / __NFDBITS];
	#define __FDS_BITS(set) ((set)->__fds_bits)
#endif
} fd_set
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页