On 2026-10-31, Lawrence D’Oliveiro <l…@nz.invalid> wrote:
> On Sat, 31 Oct 2026 04:14:05 GMT, Charlie Gibbs wrote: >
>> I've always tried to avoid the complexities of threading; in most >> cases I can get away with round-robin scheduling. But I found that >> some servers are very slow to respond, and even when trying to do a >> non-blocking setup of a TCP/IP connection, the connect() API would >> unavoidably block. I had to spin that part off into its own thread >> to keep the rest of the program (including other connections) from >> hanging.
> > Here’s a fun little thing: if you set a socket to nonblocking and then > do the connect(2) call, it will seemingly fail with an EINPROGRESS > error. But in fact, the connection attempt gets initiated, and you can > monitor its subsequent progress from your event loop. > > From the ERRORS section of <https://manpages.debian.org/connect(2)>: > > EINPROGRESS > The socket is nonblocking and the connection cannot be > completed immediately. (UNIX domain sockets failed with EAGAIN > instead.) It is possible to select(2) or poll(2) for > completion by selecting the socket for writing. After > select(2) indicates writability, use getsockopt(2) to read the > SO_ERROR option at level SOL_SOCKET to determine whether > connect() completed successfully (SO_ERROR is zero) or > unsuccessfully (SO_ERROR is one of the usual error codes > listed here, explaining the reason for the failure). > > I’m not sure about doing this sort of thing from other libraries that > wrap socket connections (e.g. SSL/TLS libraries); for these, the usual > fallback is still available, as you say, by turning a blocking call > into a nonblocking one by pushing it off to a separate thread.
I was already setting the socket to non-blocking before calling connect() - and yet there were times when the API blocked anyway. I never did figure out why, and we had a customer getting impatient, so I just spun off another thread and moved on to other things.
-- /~\ Charlie Gibbs | In this world there are \ / <cgib…@kltpzyxm.invalid> | two kinds of people: X I'm really at ac.dekanfrus | 1. Those who can extrapolate / \ if you read it the right way. | from incomplete data.