如何在套接字上正确使用select()? [英] How to use select() on sockets properly?

查看:161
本文介绍了如何在套接字上正确使用select()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在套接字上调用select,我不明白自己在做什么错.

setup_server_socket调用bindlisten并将套接字设置为非阻塞模式.

似乎在select上的以下代码块被调用,而不是前进到FD_ISSET.我尝试连接客户端,但似乎成功,但select从未返回任何内容.

执行此操作的正确方法是什么?

...
int listenfd = setup_server_socket( serverPort );

if( -1 == listenfd )
    return 1;

fd_set read_fds;
FD_ZERO(&read_fds);
int fdmax = listenfd;


// loop forever
while( 1 )
{
    if (select(fdmax+1, &read_fds, NULL,NULL,NULL) == -1){
        perror("select");
        exit(4);
    }

    for (int i = 0; i<= fdmax; i++){
        printf("Testing: %d, %d\n", i, FD_ISSET(i,&read_fds));

    }return 0;
...

解决方案

阅读多次投票(2 (顺便说一句,您应该更喜欢poll而不是过时的select,后者不处理大于__FD_SETSIZE的文件描述符,即在我的Linux/Debian/x86-64系统上为1024). >

然后:

fd_set read_fds;
FD_ZERO(&read_fds);
int fdmax = listenfd;
FD_SET(listenfd, &read_fds);

在调用select之前,应该进入循环内的 .顺便说一句,我建议使用poll代替select

还请阅读有关 C10k问题

别忘了select正在更改其给定的fd_set -s(通常希望它们为非空)...

也许使用 strace(1)

也请阅读高级Linux编程(这是一本免费的书,您也可以在纸上阅读,也可以从中下载其他几个地方,例如等...)

I'm trying to wrap my head around calling select on sockets and I can't understand what I'm doing wrong.

setup_server_socket calls bind and listen and sets the socket to nonblocking mode.

The following code blocks on the select call it seems, not moving forward to FD_ISSET. I tried connecting a client and it seems to succeed but select never returns anything.

What's the proper way to do this?

...
int listenfd = setup_server_socket( serverPort );

if( -1 == listenfd )
    return 1;

fd_set read_fds;
FD_ZERO(&read_fds);
int fdmax = listenfd;


// loop forever
while( 1 )
{
    if (select(fdmax+1, &read_fds, NULL,NULL,NULL) == -1){
        perror("select");
        exit(4);
    }

    for (int i = 0; i<= fdmax; i++){
        printf("Testing: %d, %d\n", i, FD_ISSET(i,&read_fds));

    }return 0;
...

解决方案

Read several times select(2), poll(2) (BTW, you should prefer poll to the obsolete select, which don't handle file descriptors bigger than __FD_SETSIZE, i.e. 1024 on my Linux/Debian/x86-64 system).

Then:

fd_set read_fds;
FD_ZERO(&read_fds);
int fdmax = listenfd;
FD_SET(listenfd, &read_fds);

should go inside the while(1) loop, before calling select. BTW, I recommend using poll instead of select

Read also about the C10k problem

Don't forget that select is changing its given fd_set-s (and usually wants them to be non-empty)...

Perhaps use strace(1)

Read also Advanced Linux Programming (it is a free book that you could also read on paper, or download from several other places, e.g. this etc...)

这篇关于如何在套接字上正确使用select()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆