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