Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 17.2 UNIX Domain Sockets 631


Example — Polling XSI Message Queues with the Help of UNIX Domain Sockets


In Section 15.6.4, we said one of the problems with using XSI message queues is that we
can’t use poll or select with them, because they aren’t associated with file
descriptors. However,socketsareassociated with file descriptors, and we can use them
to notify us when messages arrive. We’ll use one thread per message queue. Each
thread will block in a call tomsgrcv.When a message arrives, the thread will write it
down one end of a UNIX domain socket. Our application will use the other end of the
socket to receive the message whenpollindicates data can be read from the socket.
The program in Figure17.3 illustrates this technique. Themainfunction creates the
message queues and UNIX domain sockets and starts one thread to service each queue.
Then it uses an infinite loop to poll one end of the sockets. When a socket is readable, it
reads from the socket and writes the message on the standardoutput.
#include "apue.h"
#include <poll.h>
#include <pthread.h>
#include <sys/msg.h>
#include <sys/socket.h>
#define NQ 3/*number of queues */
#define MAXMSZ 512 /* maximum message size */
#define KEY 0x123 /* key for first message queue */
struct threadinfo {
int qid;
int fd;
};
struct mymesg {
long mtype;
char mtext[MAXMSZ];
};
void *
helper(void *arg)
{
int n;
struct mymesg m;
struct threadinfo *tip = arg;
for(;;) {
memset(&m, 0, sizeof(m));
if ((n = msgrcv(tip->qid, &m, MAXMSZ, 0, MSG_NOERROR)) < 0)
err_sys("msgrcv error");
if (write(tip->fd, m.mtext, n) < 0)
err_sys("write error");
}
}
int
main()
Free download pdf