A non-blocking connection is performed. Under windows, the moment of installing a socket can be defined using select, if the socket is writable, then the connection is established. And how under linux? After initialization, it immediately becomes writable. And accordingly, an attempt to write something to the socket will call SIGPIPE.

int sockfd = ::socket(AF_INET, SOCK_STREAM, 0); int arg = ::fcntl(sockfd, F_GETFL); long flags = arg & ~O_NONBLOCK; flags |= O_NONBLOCK; fcntl(sockfd, F_SETFL, flags); struct sockaddr_in dest; dest.sin_family = AF_INET; dest.sin_port = htons(1111); inet_aton("127.0.0.1", &dest.sin_addr); int rc = ::connect(sockfd, (struct sockaddr* )&dest, sizeof(dest)); fd_set fdWrite; FD_ZERO(&fdWrite); FD_SET(sockfd, &fdWrite); struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; rc = ::select(int(sockfd) + 1, 0, &fdWrite, 0, &tv); int er = errno; return 0; 
  • 2
    Do you really need a non-blocking socket? For some reason, 75% of beginners working with sockets are trying to use non-blocking ones. But in real server applications there are no such sockets, simply because select was invented specifically to stop using them! Especially to get away from the polling algorithms. Read what Sean Walton writes in his book “Creating Network Applications in the Linux Environment. He discusses non-blocking sockets there, but all examples of specific applications are written WITHOUT this“ manual control. ” - Sergey
  • A minimal reproducible example for experiments would help the question ... - Fat-Zer
  • 3
    @Sergey By the way, if the socket is blocking, then connect is guaranteed to block the entire stream until the moment it establishes the connection, which is not acceptable for an asynchronous application - Mike
  • one
    @Mike connect is guaranteed to block the entire stream until the moment it establishes the connection - Three questions (I propose to think): 1) What is the flow? 2) What are you going to read from a non-blocking socket if there is no data? 3) Where are you going to write if the socket is not ready to write? :-) - Sergey
  • one
    You can use non-blocking sockets only in a single-threaded server. And even then - if you really want hemorrhoids :-) Understand, select was invented for the ENABLING of the life of programmers. You just have to sit down and deal with it once! - Sergey

1 answer 1

In order not to pull the rubber leading questions, I just quote man 2 connect

ERRORS

...
EINPROGRESS

The socket is non-blocking, and the connection cannot be established immediately. You can use select (2) or poll (2) to end the connection by setting the wait for write to the socket. After select (2) reports this possibility, use getsockopt (2) to read the SO_ERROR flag at the SOL_SOCKET level to determine if connect () completed successfully (in this case, SO_ERROR is zero) or unsuccessful (then SO_ERROR is one of the common error codes listed here and explains the reason for the failure).