Team BBL
Previous Page Next Page

Chapter 16

16.1

Figure C.20 shows a program that prints the system's byte order.

Figure C.20. Determine byte order on system
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

int
main(void)
{
    uint32_t i;
    unsigned char *cp;

    i = 0x04030201;
    cp = (unsigned char *)&i;
    if (*cp == 1)
        printf("little-endian\n");
    else if (*cp == 4)
        printf("big-endian\n");
    else
        printf("who knows?\n");
    exit(0);
}

16.3

For each endpoint we will be listening on, we need to bind the proper address and record an entry in an fd_set structure corresponding to each file descriptor.

We will use select to wait for connect requests to arrive on multiple endpoints. Recall from Section 16.4 that a passive endpoint will appear to be readable when a connect request arrives on it. When a connect request does arrive, we will accept the request and process it as before.

16.5

In the main procedure, we need to arrange to catch SIGCHLD by calling our signal function (Figure 10.18), which will use sigaction to install the handler specifying the restartable system call option. Next, we need to remove the call to waitpid from our serve function. After forking the child to service the request, the parent closes the new file descriptor and resumes listening for additional connect requests. Finally, we need a signal handler for SIGCHLD, as follows:

     void
     sigchld(int signo)
     {
         while (waitpid((pid_t)-1, NULL, WNOHANG) > 0)
             ;
     }

16.6

To enable asynchronous socket I/O, we need to establish socket ownership using the F_SETOWN fcntl command, and then enable asynchronous signaling using the FIOASYNC ioctl command. To disable asynchronous socket I/O, we simply need to disable asynchronous signaling. The reason we mix fcntl and ioctl commands is to find the methods that are most portable. The code is shown in Figure C.21.

Figure C.21. Enable and disable asynchronous socket I/O
#include "apue.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#if defined(BSD) || defined(MACOS) || defined(SOLARIS)
#include <sys/filio.h>
#endif

int
setasync(int sockfd)
{
    int n;

    if (fcntl(sockfd, F_SETOWN, getpid()) < 0)
        return(-1);
    n = 1;
    if (ioctl(sockfd, FIOASYNC, &n) < 0)
        return(-1);
    return(0);
}

int
clrasync(int sockfd)
{
    int n;

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

    Team BBL
    Previous Page Next Page