If you create a
blocking socket, which is the default, then well... operations like
connect()
,
send()
and
recv()
are going to
block the calling thread. If you want to avoid the "main" thread to get blocked, you could move the call to a separate "worker" thread, but then there still is
no clean way to "abort" the operation from another thread. What you
can do is setting up a
time-out for these operations, so that the calling thread won't be blocked forever. Specifically, you may want to set
SO_RCVTIMEO
and
SO_SNDTIMEO
via the
setsockopt()
function.
According to the manpage:
https://man7.org/linux/man-pages/man7/socket.7.html
Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached, then -1 is returned with errno set to EAGAIN or EWOULDBLOCK, or EINPROGRESS (for connect(2)) just as if the socket was specified to be nonblocking. If the timeout is set to zero (the default), then the operation will never timeout. Timeouts only have effect for system calls that perform socket I/O (e.g., accept(2), connect(2), read(2), recvmsg(2), send(2), sendmsg(2)) [...] |
Your other option is to use
non-blocking sockets, e.g., by passing the
SOCK_NONBLOCK
flag to
socket()
when creating the socket, or by using the
fcntl()
function with the
O_NONBLOCK
flag to switch an existing socket into non-blocking mode. This way, operations like
connect()
,
send()
and
recv()
will
not block at all, but rather return immediately with an error code like
EAGAIN
or
EWOULDBLOCK
(or
EINPROGRESS
).
Instead of repeatedly re-trying the operation on the non-blocking socket in a loop (which is very inefficient), you would then use the
poll()
(or
epoll
) mechanism to figure out
when a socket becomes ready for reading and/or writing:
https://man7.org/linux/man-pages/man2/poll.2.html
Note that
poll()
allows you to "monitor" multiple sockets at the same time, so you can react as soon as
any of them becomes ready. Also, the
poll()
function has an explicit time-out parameter, so you can be sure it will return after this amount of time.