Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

c - Reusing socket descriptor on connection failure

In my client code, I am following these steps to connect to a socket:

  1. Creating a socket

    sockDesc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)  
    
  2. Connecting it (retry for 'x' time in case of failure)

    connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr))  
    

    (After filling the destAddr fields)

  3. Using the socket for send()/recv() operation:

    send(sockDesc, buffer, bufferLen, 0)  
    recv(sockDesc, buffer, bufferLen, 0)  
    
  4. close() the socket descriptor and exit

    close(sockDesc)  
    

If during send()/recv() the connection breaks, I found that I could connect by returning to step 2.

Is this solution okay? should I close the socket descriptor and return to step 1?

Another interesting observation that I am not able to understand is when I stop my echo server and start the client. I create a Socket (step 1) and call connect() which fails (as expected) but then I keep calling connect(), lets say, 10 times. After 5 retries I start the server and connect() is successful. But during the send() call it receives SIGPIPE error. I would like to know:

1) Do I need to create a new socket every time connect() fails? As per my understanding as long as I have not performed any send()/recv() on the socket it is as good as new and I can reuse the same fd for the connect() call.

2) I don't understand why SIGPIPE is received when the server is up and connect() is successful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you should close and go back to step 1:

close() closes a file descriptor, so that it no longer refers to any file and may be reused.

From here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...