PDA

View Full Version : Exiting socket gracefully



vkaushal21
09-07-2009, 10:38 AM
I am writing a socket ...

When I call accept function, it keeps on waiting for the new connection.

I want to know, can I call accept function in some manner so that it doesn't completely hang the execution. I don't want to use Ctrl+C to exit the server everytime.

I know threading is an option, but some other better option?

MK27
09-07-2009, 10:53 AM
Use non-block.


The accept function waits if there are no connections pending, unless the socket socket has nonblocking mode set. (You can use select to wait for a pending connection, with a nonblocking socket.)

You set non-block like this:


#include <fcntl.h>
fcntl(socket_fd,F_SETFL,O_NONBLOCK);

Tesctassa
09-09-2009, 03:20 AM
I am writing a socket ...

When I call accept function, it keeps on waiting for the new connection.

I want to know, can I call accept function in some manner so that it doesn't completely hang the execution. I don't want to use Ctrl+C to exit the server everytime.

I know threading is an option, but some other better option?

Google for "non-blocking socket". You should find a lot of examples about it. I had the same doubt.

(=

Kennedy
09-09-2009, 11:06 AM
Try using select() on it. Configure an internal pipe that you can use to break out of the select wait state (if you need to break out for some reason --- like your main tread is exiting)