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