Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle EINTR in connect()?

I'm trying to handle EINTR error from POSIX connect call. I'm running on OSX this connect code:

JNIEXPORT jint JNICALL Java_io_questdb_network_Net_connect
        (JNIEnv *e, jclass cl, jint fd, jlong sockAddr) {
    jboolean retry = 0;
    int result;
    do {
        result = connect((int) fd, (const struct sockaddr *) sockAddr, sizeof(struct sockaddr));
        retry |= result == -1 && errno == EINTR;
    } while (result == -1 && errno == EINTR);

    if (retry && errno == EISCONN) {
        return 0;
    }
    return result;
}

This is JNI code I call from Java. When I run the code under the profiler, I quite often get EINTR. Sometimes after running this connect() method, I get ENOTCONN on next send() call using the socket.

If I remove

if (retry && errno == EISCONN) {
        return 0;
}

I start to get EISCONN very often when calling this method.

How can I properly handle EINTR here so the socket is connected at the end of the call?

like image 754
Alex des Pelagos Avatar asked Dec 22 '25 13:12

Alex des Pelagos


1 Answers

There is no need for the retry variable. Just do:

int result;
do {
    result = ...
} while (result == -1 && errno == EINTR); //on error result will be -1,
                                          //additional test for EINTR,
                                          //if both are true, try again

//the same goes for EISCONN
if (result == -1 && errno == EISCONN) {
    //already connected
    //usually an error, but we consider it as success
    return 0;
}

return result; //0 on success, -1 on error

The return value will be 0 if connect succeeded or if already connected, or -1 in all other error cases.

man connect

If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

like image 118
Erdal Küçük Avatar answered Dec 24 '25 03:12

Erdal Küçük



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!