views:

232

answers:

2

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?

+1  A: 

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

nos
A: 

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).

JesperE