Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

940 Solutions to Selected Exercises Appendix C


int
clrasync(int sockfd)
{
int n;
n=0;
if (ioctl(sockfd, FIOASYNC, &n) < 0)
return(-1);
return(0);
}

Figure C.23 Enable and disable asynchronous socket I/O

Chapter 17


17.1 Regular pipes provide a byte stream interface. To detect message boundaries,
we’d have to add a header to each message to indicate the length. But this still
involves two extra copy operations: one to write to the pipe and one to read from
the pipe. Amoreefficient approach is to use the pipe only to signal the main
thread that a new message is available. We can use a single byte for this
purpose. With this approach, we need to move themymesgstructure to the
threadinfostructureand use a mutex and a condition variable to prevent the
helper thread from reusing themymesgstructureuntil the main thread is done
with it. The solution is shown in FigureC.24.
#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 mymesg {
long mtype;
char mtext[MAXMSZ+1];
};

struct threadinfo {
int qid;
int fd;
int len;
pthread_mutex_t mutex;
pthread_cond_t ready;
struct mymesg m;
};
Free download pdf