Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

942 Solutions to Selected Exercises Appendix C


for (;;) {
if (poll(pfd, NQ, -1) < 0)
err_sys("poll error");
for (i = 0; i < NQ; i++) {
if (pfd[i].revents & POLLIN) {
if ((n = read(pfd[i].fd, &c, sizeof(char))) < 0)
err_sys("read error");
ti[i].m.mtext[ti[i].len] = 0;
printf("queue id %d, message %s\n", qid[i],
ti[i].m.mtext);
pthread_mutex_lock(&ti[i].mutex);
pthread_cond_signal(&ti[i].ready);
pthread_mutex_unlock(&ti[i].mutex);
}
}
}

exit(0);
}

Figure C.24 Poll for XSI messages using pipes

17.3 Adeclarationspecifies the attributes (such as the data type) of a set of identifiers.
If the declaration also causes storage to be allocated, it is called adefinition.
In theopend.hheader, we declarethe three global variables with theextern
storage class. These declarations do not cause storage to be allocated for the
variables. In themain.cfile, we define the three global variables. Sometimes,
we’ll also initialize a global variable when we define it, but we typically let the C
default apply.
17.5 Bothselectandpollreturn the number of ready descriptors as the value of
the function. The loop that goes through theclientarray can terminate when
the number of ready descriptors has been processed.

17.6 The first problem with the proposed solution is that there is a race between the
call tostatand the call tounlinkwherethe file can change. The second
problem is that if the name is a symbolic link pointing to the UNIX domain
socket file, thenstatwill report that the name is a socket (recall that thestat
function follows symbolic links), but when we callunlink, we will actually
remove the symbolic link instead of the socket file. To solve this problem, we
should uselstatinstead ofstat,but this doesn’t solve the first problem.
17.7 The first option is to send both file descriptors in one control message. Each file
descriptor is stored in adjacent memory locations. The following code shows
this:
struct msghdr msg;
struct cmsghdr *cmptr;
int *ip;
Free download pdf