1*62785Sbostic .\" Copyright (c) 1986, 1993 2*62785Sbostic .\" The Regents of the University of California. All rights reserved. 348154Sbostic .\" 448154Sbostic .\" %sccs.include.redist.roff% 548154Sbostic .\" 6*62785Sbostic .\" @(#)socketpair.c 8.1 (Berkeley) 06/08/93 748154Sbostic .\" 827700Smckusick #include <sys/types.h> 927700Smckusick #include <sys/socket.h> 1027700Smckusick #include <stdio.h> 1127700Smckusick 1227700Smckusick #define DATA1 "In Xanadu, did Kublai Khan . . ." 1327700Smckusick #define DATA2 "A stately pleasure dome decree . . ." 1427700Smckusick 1527700Smckusick /* 1627700Smckusick * This program creates a pair of connected sockets then forks and 1727700Smckusick * communicates over them. This is very similar to communication with pipes, 1827700Smckusick * however, socketpairs are two-way communications objects. Therefore I can 1927700Smckusick * send messages in both directions. 2027700Smckusick */ 2127700Smckusick 2227700Smckusick main() 2327700Smckusick { 2427883Skarels int sockets[2], child; 2527883Skarels char buf[1024]; 2627700Smckusick 2727883Skarels if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) { 2827700Smckusick perror("opening stream socket pair"); 2927883Skarels exit(1); 3027883Skarels } 3127883Skarels 3227883Skarels if ((child = fork()) == -1) 3327883Skarels perror("fork"); 3427883Skarels else if (child) { /* This is the parent. */ 3527700Smckusick close(sockets[0]); 3627700Smckusick if (read(sockets[1], buf, 1024, 0) < 0) 3727700Smckusick perror("reading stream message"); 3827700Smckusick printf("-->%s\en", buf); 3927700Smckusick if (write(sockets[1], DATA2, sizeof(DATA2)) < 0) 4027700Smckusick perror("writing stream message"); 4127700Smckusick close(sockets[1]); 4227700Smckusick } else { /* This is the child. */ 4327700Smckusick close(sockets[1]); 4427700Smckusick if (write(sockets[0], DATA1, sizeof(DATA1)) < 0) 4527700Smckusick perror("writing stream message"); 4627700Smckusick if (read(sockets[0], buf, 1024, 0) < 0) 4727700Smckusick perror("reading stream message"); 4827700Smckusick printf("-->%s\en", buf); 4927700Smckusick close(sockets[0]); 5027700Smckusick } 5127700Smckusick } 52