Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

630 Advanced IPC Chapter 17


#include <sys/socket.h>
int socketpair(intdomain,int type,intprotocol,intsockfd[2]);
Returns: 0 if OK,−1 on error
Although the interface is sufficiently general to allowsocketpairto be used with
other domains, operating systems typically provide support only for the UNIX domain.

socket socket

fd[0] fd[1]

user process

Figure 17.1 Asocket pair

Apair of connected UNIX domain sockets acts like a full-duplex pipe: both ends are
open for reading and writing (see Figure17.1). We’ll refer to these as ‘‘fd-pipes’’to
distinguish them from normal, half-duplex pipes.

Example —fd_pipeFunction


Figure17.2 shows thefd_pipefunction, which uses thesocketpairfunction to
create a pair of connected UNIX domain stream sockets.
#include "apue.h"
#include <sys/socket.h>
/*
*Returns a full-duplex pipe (a UNIX domain socket) with
*the two file descriptors returned in fd[0] and fd[1].
*/
int
fd_pipe(int fd[2])
{
return(socketpair(AF_UNIX, SOCK_STREAM, 0, fd));
}

Figure 17.2Creating a full-duplex pipe

Some BSD-based systems use UNIX domain sockets to implement pipes. But whenpipeis
called, the write end of the first descriptor and the read end of the second descriptor areboth
closed. Toget a full-duplex pipe, we must callsocketpairdirectly.
Free download pdf