Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

666 Advanced IPC Chapter 17


argument toselect.Wealso keep track of the highest index in use in the
clientarray.)


  1. An existing client’s connection can be ready for reading. This means that the
    client has either terminated or sent a new request. Wefind out about a client
    termination byreadreturning 0 (end of file). Ifreadreturns a value greater
    than 0, there is a new request to process, which we handle by calling
    handle_request.
    We keep track of which descriptors arecurrently in use in theallsetdescriptor
    set. As new clients connect to the server,the appropriate bit is turned on in this
    descriptor set. The appropriate bit is turned offwhen the client terminates.
    We always know when a client terminates, whether the termination is voluntary or
    not, since all the client’s descriptors (including the connection to the server) are
    automatically closed by the kernel. This differs from the XSI IPC mechanisms.
    Theloopfunction that usespollis shown in Figure17.30.
    #include "opend.h"
    #include <poll.h>


#define NALLOC 10 /*#pollfd structs to alloc/realloc */

static struct pollfd *
grow_pollfd(struct pollfd *pfd, int *maxfd)
{
int i;
int oldmax=*maxfd;
int newmax=oldmax + NALLOC;

if ((pfd = realloc(pfd, newmax * sizeof(struct pollfd))) == NULL)
err_sys("realloc error");
for (i = oldmax; i < newmax; i++) {
pfd[i].fd = -1;
pfd[i].events = POLLIN;
pfd[i].revents = 0;
}
*maxfd = newmax;
return(pfd);
}

void
loop(void)
{
int i, listenfd, clifd, nread;
char buf[MAXLINE];
uid_t uid;
struct pollfd *pollfd;
int numfd=1;
int maxfd=NALLOC;

if ((pollfd = malloc(NALLOC * sizeof(struct pollfd))) == NULL)
err_sys("malloc error");
Free download pdf