127700Smckusick .\" Copyright (c) 1986 Regents of the University of California.
227700Smckusick .\" All rights reserved.  The Berkeley software License Agreement
327700Smckusick .\" specifies the terms and conditions for redistribution.
427700Smckusick .\"
5*27883Skarels .\"	@(#)socketpair.c	6.2 (Berkeley) 05/08/86
627700Smckusick .\"
727700Smckusick #include <sys/types.h>
827700Smckusick #include <sys/socket.h>
927700Smckusick #include <stdio.h>
1027700Smckusick 
1127700Smckusick #define DATA1 "In Xanadu, did Kublai Khan . . ."
1227700Smckusick #define DATA2 "A stately pleasure dome decree . . ."
1327700Smckusick 
1427700Smckusick /*
1527700Smckusick  * This program creates a pair of connected sockets then forks and
1627700Smckusick  * communicates over them.  This is very similar to communication with pipes,
1727700Smckusick  * however, socketpairs are two-way communications objects. Therefore I can
1827700Smckusick  * send messages in both directions.
1927700Smckusick  */
2027700Smckusick 
2127700Smckusick main()
2227700Smckusick {
23*27883Skarels 	int sockets[2], child;
24*27883Skarels 	char buf[1024];
2527700Smckusick 
26*27883Skarels 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
2727700Smckusick 		perror("opening stream socket pair");
28*27883Skarels 		exit(1);
29*27883Skarels 	}
30*27883Skarels 
31*27883Skarels 	if ((child = fork()) == -1)
32*27883Skarels 		perror("fork");
33*27883Skarels 	else if (child) {	/* This is the parent. */
3427700Smckusick 		close(sockets[0]);
3527700Smckusick 		if (read(sockets[1], buf, 1024, 0) < 0)
3627700Smckusick 			perror("reading stream message");
3727700Smckusick 		printf("-->%s\en", buf);
3827700Smckusick 		if (write(sockets[1], DATA2, sizeof(DATA2)) < 0)
3927700Smckusick 			perror("writing stream message");
4027700Smckusick 		close(sockets[1]);
4127700Smckusick 	} else {		/* This is the child. */
4227700Smckusick 		close(sockets[1]);
4327700Smckusick 		if (write(sockets[0], DATA1, sizeof(DATA1)) < 0)
4427700Smckusick 			perror("writing stream message");
4527700Smckusick 		if (read(sockets[0], buf, 1024, 0) < 0)
4627700Smckusick 			perror("reading stream message");
4727700Smckusick 		printf("-->%s\en", buf);
4827700Smckusick 		close(sockets[0]);
4927700Smckusick 	}
5027700Smckusick }
51