socket programming and pthread

Hi, how can a server knows that a client has left the socket?
I wish to have the server returns to the accept(*listenSocket....) command to wait for new client when a connected client has exit...
By left I take it you mean closed, is that right? If the client doesn't close it, the server can't know until TCP times out the connection.

The server should always go back to listening for new connections irrespective of whether the client is open or not. This is a multithreaded app right?
I have some code that I found on the internet a while ago that I have never tested. It is supposed to test if the client has closed the connection over a socket:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <sys/types.h>       // For data types
#include <sys/socket.h>      // For socket(), connect(), send(), and recv()
#include <poll.h>          // For poll()

bool is_client_closed(int cs)
{
	pollfd pfd;
	pfd.fd = cs;
	pfd.events = POLLIN | POLLHUP | POLLRDNORM;
	pfd.revents = 0;
	while(pfd.revents == 0)
	{
		// call poll with a timeout of 100 ms
		if(poll(&pfd, 1, 100) > 0)
		{
			// if result > 0, this means that there is either data available on the
			// socket, or the socket has been closed
			char buffer[32];
			if(recv(cs, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0)
			{
				// if recv returns zero, that means the connection has been closed:
				return true;
			}
		}
	}
	return false;
}

If you try it, let us know if it works :)
Topic archived. No new replies allowed.