2
votes

I have the following code in C.

void setNonBlocking(SOCKET fd){
    int flags;
    if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
        flags = 0;

    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

int main(){

int sock;
connect(sock, .....);
setNonBlocking(sock);
....
close(sock);

//we will do something here but the application exits in/after the close operation

}

I am using the socket in non-blocking mode with setNonBlocking function. When i close socket, the application immediately exits without segfault or anything else. I don't see this issue if i don't use setNonBlocking function.

How can i close the non-blocking socket without this issue?

2
Run your code under GDB. The behavior you're describing (close causing application exit without crash) is pretty much impossible. - diciu
Have you created a socket using the socket() function? This is missing in your code. You declare sock (which at this point contains garbage or 0) and then you call connect. - Frunsi
Can you explain more about how you do send/receive etc in your code? That might be more helpful. Normally close should not behave differently just because the socket is non-blocking. - Jay

2 Answers

1
votes

Perhaps your application is getting SIGPIPE. You should normally handle or ignore the SIGPIPE signal when programming with sockets.

0
votes

You are ignoring any error-result from fcntl. If fcntl returns -1, you should at least print out an error message (using perror, for example).