By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,144 Members | 872 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,144 IT Pros & Developers. It's quick & easy.

Socket Port going to CLOSE_WAIT after repeated accept

P: 1
Hi All,

I have written an application, a part of which, in the application, is a socket server programe accepting connection requests from socket clients.

My server code typically contains,

a call to socket, bind, listen, accept and later read and write using the accept file descriptor (fd).

The client socket prog is so designed (who ever did so!) that every certain time period it closes the connection with the server and reconnects again with the server.

To handle the same how I have designed my code is, when my application finds that the connection with the client is closed it calls the accept function again to accept new connection request from the client.

Before accepting a new connection I was not closing the exiting accept fd.

This was working fine for some time but recently when I had to leave the application running for a longer time, I noticed that there were too many instances of the port (to which the server and client were talking) were in CLOSE_WAIT state, which sure was looking annoying and obiously not good for the system.

Trying to dig into what could be the possible reason, thinking that since I was not closing the accept fd before accepting the new connection request from the client, I introduced a close system call before the accept call to cose the previous accepted fd.

But this gives me a bizarre response like the client comes down immediately after reconnection etc.

I would be thankful if anyone could please help me on this as to how to handle this scenerio.

PS: Sorry for a long explanation :(

Nov 20 '08 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 542
I've read your post partially...sorry...
However, I can tell you that, your design for server is quite wrong..
Ideally...You should fork a new process or thread after accepting the connection from client. And wait for another connection request.
It doesn't even matters that how many times client closes the connection and reconnect to server.
Code should look something like this

//socket initialization and etc.
pid = fork();
if( pid == 0 )
//Do what you want to do here,read/write etc


accept() always returns new socket descriptor. And you are supposed to read/write using that fd.
So, whenever your client connects to server, It'll be communicating with it by new socket.

Nov 20 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.