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.2 (Berkeley) 05/08/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 		exit(1);
29 	}
30 
31 	if ((child = fork()) == -1)
32 		perror("fork");
33 	else if (child) {	/* This is the parent. */
34 		close(sockets[0]);
35 		if (read(sockets[1], buf, 1024, 0) < 0)
36 			perror("reading stream message");
37 		printf("-->%s\en", buf);
38 		if (write(sockets[1], DATA2, sizeof(DATA2)) < 0)
39 			perror("writing stream message");
40 		close(sockets[1]);
41 	} else {		/* This is the child. */
42 		close(sockets[1]);
43 		if (write(sockets[0], DATA1, sizeof(DATA1)) < 0)
44 			perror("writing stream message");
45 		if (read(sockets[0], buf, 1024, 0) < 0)
46 			perror("reading stream message");
47 		printf("-->%s\en", buf);
48 		close(sockets[0]);
49 	}
50 }
51