1*27700Smckusick .\" Copyright (c) 1986 Regents of the University of California. 2*27700Smckusick .\" All rights reserved. The Berkeley software License Agreement 3*27700Smckusick .\" specifies the terms and conditions for redistribution. 4*27700Smckusick .\" 5*27700Smckusick .\" @(#)socketpair.c 6.1 (Berkeley) 05/04/86 6*27700Smckusick .\" 7*27700Smckusick #include <sys/types.h> 8*27700Smckusick #include <sys/socket.h> 9*27700Smckusick #include <stdio.h> 10*27700Smckusick 11*27700Smckusick #define DATA1 "In Xanadu, did Kublai Khan . . ." 12*27700Smckusick #define DATA2 "A stately pleasure dome decree . . ." 13*27700Smckusick 14*27700Smckusick /* 15*27700Smckusick * This program creates a pair of connected sockets then forks and 16*27700Smckusick * communicates over them. This is very similar to communication with pipes, 17*27700Smckusick * however, socketpairs are two-way communications objects. Therefore I can 18*27700Smckusick * send messages in both directions. 19*27700Smckusick */ 20*27700Smckusick 21*27700Smckusick main() 22*27700Smckusick { 23*27700Smckusick int sockets[2], child; 24*27700Smckusick char buf[1024]; 25*27700Smckusick 26*27700Smckusick if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) 27*27700Smckusick perror("opening stream socket pair"); 28*27700Smckusick if (child = fork()) { /* This is the parent. */ 29*27700Smckusick close(sockets[0]); 30*27700Smckusick if (read(sockets[1], buf, 1024, 0) < 0) 31*27700Smckusick perror("reading stream message"); 32*27700Smckusick printf("-->%s\en", buf); 33*27700Smckusick if (write(sockets[1], DATA2, sizeof(DATA2)) < 0) 34*27700Smckusick perror("writing stream message"); 35*27700Smckusick close(sockets[1]); 36*27700Smckusick } else { /* This is the child. */ 37*27700Smckusick close(sockets[1]); 38*27700Smckusick if (write(sockets[0], DATA1, sizeof(DATA1)) < 0) 39*27700Smckusick perror("writing stream message"); 40*27700Smckusick if (read(sockets[0], buf, 1024, 0) < 0) 41*27700Smckusick perror("reading stream message"); 42*27700Smckusick printf("-->%s\en", buf); 43*27700Smckusick close(sockets[0]); 44*27700Smckusick } 45*27700Smckusick } 46