Open System Services Programmer's Guide

fdcount = 1;
highfd = fd;
listenfd = fd;
FD_ZERO(&fdset);
FD_SET(listenfd, &fdset);
/* Find a ready socket ... */
while (1)
{
/* initialize timeout and bitmask for select() call */
timeval.tv_sec = IDLE_PERIOD;
timeval.tv_usec = 0;
memcpy(&rdset, &fdset, sizeof(fdset));
readycount = select(highfd+1, &rdset, NULL, NULL, &timeval);
/* if timeout then exit(0) */
if (readycount == 0)
{
printf("Server stopping\n");
exit(0);
}
/* find first fd that was marked ready for reading */
for (fd = 0; fd <= highfd; fd++)
{
if (FD_ISSET(fd, &rdset))
break;
}
/* if fd is listening socket, accept incoming connection */
if (fd == listenfd)
{
/* accept new connection ... if error, then exit(1) */
if ((newfd = accept(fd,(struct sockaddr *)NULL, (size_t *)NULL)) < 0)
{
printf("accept() call failed [errno %d]\n", errno);
exit(1);
}
/* add fd to fd set */
fdcount++;
FD_SET(newfd, &fdset);
if (newfd > highfd)
highfd = newfd;
}
else /* else fd is an existing connection */
{
if ((bytesread = recv(fd, msg_buff, BUFF_LEN, 0)) <= 0)
{
/* if recv error then exit(1) */
if (bytesread < 0)
{
printf("recv() call failed [errno %d]\n", errno);
exit(1);
}
else /* bytesread == 0 ... peer closed connection */
{
close(fd);
fdcount--;
FD_CLR(fd,&fdset);
}
}
else /* data received */
{
msg_buff[bytesread] = '\0'; /* make string
NULL-terminated */
printf("Message received = %s", msg_buff);
/* echo back to sender ... if error then exit(1) */
if (send(fd, msg_buff, bytesread, 0) < 0)
{
printf("send() call failed [errno %d]\n", errno);
180 Interprocess Communication