select() 可以与阻塞套接字一起使用吗?

Can select() be used with blocking sockets?

我想用select()来监控一个套接字是否有数据要读取,但我不想使用非阻塞套接字。那么select()可以和阻塞套接字一起使用吗?

我正在使用 Windows。

是的,这是 select 的全部要点

它会监视套接字上的 activity,如果您在不知道数据在那里的情况下尝试 read,这些套接字会阻塞。最重要的是,它可以在 多个 套接字上监视 activity,如果没有阻塞套接字上的 select 就无法做到这一点,除非每个套接字都在一个单独的线程。同样重要的是,它会告诉您套接字何时准备好读取 and/or 进行写入;简单地调用 readwrite 无法做到这一点。

select 的行为在这些方面甚至 documented

select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking.

当然,您也可以将它与非阻塞套接字一起使用,因为否则为了 "wait" for activity 您必须想出一个 read- sleep-read-sleep-... 循环,出于某些原因,这是次优的。