gpt4 book ai didi

c - select() 如何监控套接字?

转载 作者:行者123 更新时间:2023-12-03 11:49:56 24 4
gpt4 key购买 nike

Beej's Guide to network Programming 中所述, select() 监视一组用于读取的文件描述符(使用 recv()),一组用于写入的文件描述符(使用 send())和最后一个, 我不知道。当服务器套接字从客户端套接字接收到消息时,read_fds set 将被修改,select() 从阻塞状态返回。向客户端套接字发送消息也是一样的。例如:

for(;;) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);
}
//the rest is code for processing ready socket

我猜测此时read_fds集合将包含唯一的就绪套接字描述符(其他的都被移除),就绪套接字描述符是新连接的套接字或从连接的套接字发送的消息。我的理解正确吗?

看来ready socket必须一一处理。当我试图在 gdb 上运行它以了解其行为时,程序正在处理就绪套接字(select() 返回后的代码),我尝试发送一些消息并通过以下方式连接到服务器一些新客户。即使未调用 select(),它如何识别新客户端或新发送的消息?

最佳答案

As described in Beej's Guide to network Programming, select() monitors a set of file descriptors for reading (using recv()), a set of file descriptor for writing (using send())

and the last one, I don't know.

最后一个已经没有任何用处了。

I guess the read_fds set will contain the only ready socket descriptor at this point (the others are removed), and the ready socket descriptor is the new connected socket or message sent from connected socket. Is my understanding correct?

没错。

It seems the ready socket must be handled one by one. When I tried to run it on gdb to understand the behavior, while the program was processing the ready socket (the code after select() return), I tried to send some message and connect to the server by some new clients. How can it recognize the new clients or newly sent message, even if select() is not called?

通常当你创建一个像这样的轮询循环时,你会向循环中添加新的套接字。也就是说,您会在下次调用 select 之前将它们添加到适当的 fd_sets。

当新套接字变为可写时,您将在其上发送

关于c - select() 如何监控套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8429577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com