同时使用accept()和select()? [英] Using accept() and select() at the same time?

查看:382
本文介绍了同时使用accept()和select()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件驱动的网络服务器程序.该程序接受来自其他主机上其他进程的连接.同一远程IP上的不同端口可能存在许多短暂的连接.

I've got an event-driven network server program. This program accepts connections from other processes on other hosts. There may be many short-lived connections from different ports on the same remote IP.

当前,我有一个while(1)循环,该循环调用accept(),然后产生一个线程来处理新连接.读取消息后,将关闭每个连接.在远端,发送消息后,连接将关闭.

Currently, I've got a while(1) loop which calls accept() and then spawns a thread to process the new connection. Each connection is closed after the message is read. On the remote end, the connection is closed after a message is sent.

我想通过缓存打开的套接字FD来消除建立和拆除连接的开销.在发送方,这很容易-我只是不关闭连接,而是保持连接.

I want to eliminate the overhead of setting up and tearing down connections by caching the open socket FDs. On the sender side, this is easy - I just don't close the connections, and keep them around.

在接收器端,它要难一些.我知道我可以将accept()返回的FD存储在结构中,并使用poll()select()在所有此类套接字上侦听消息,但是我想同时通过accept() 监听所有缓存的连接.

On the receiver side, it's a bit harder. I know I can store the FD returned by accept() in a structure and listen for messages across all such sockets using poll() or select(), but I want to simultaneously both listen for new connections via accept() and listen on all the cached connections.

如果我使用两个线程,一个在poll()上,另一个在accept()上,那么当accept()调用返回(打开一个新的连接)时,我必须唤醒另一个线程,等待旧的线程集连接.我知道我可以使用信号和pselect()来完成此操作,但是对于如此简单的操作,整个混乱似乎太费劲了.

If I use two threads, one on poll() and one on accept(), then when the accept() call returns (a new connection is opened), I have to wake up the other thread waiting on the old set of connections. I know I can do this with a signal and pselect(), but this whole mess seems like way too much work for something so simple.

是否有通话或高级方法可以让我同时处理正在打开的新连接和在旧连接上发送的数据?

Is there a call or superior methodology that will let me simultaneously handle new connections being opened and data being sent on old connections?

推荐答案

我上次检查时,您可以先在套接字上listen然后在selectpoll上查看是否有连接进入. ,accept它;它不会阻止(但您可能想要 确实应该设置O_NONBLOCK以确保确定)

Last time I checked, you could just listen on a socket and then select or poll to see if a connection came in. If so, accept it; it will not block (but you may want to really should set O_NONBLOCK just to be sure)

这篇关于同时使用accept()和select()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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