Path: blob/main/share/doc/psd/20.ipctut/socketpair.c
39530 views
.\" Copyright (c) 1986, 19931.\" The Regents of the University of California. All rights reserved.2.\"3.\" Redistribution and use in source and binary forms, with or without4.\" modification, are permitted provided that the following conditions5.\" are met:6.\" 1. Redistributions of source code must retain the above copyright7.\" notice, this list of conditions and the following disclaimer.8.\" 2. Redistributions in binary form must reproduce the above copyright9.\" notice, this list of conditions and the following disclaimer in the10.\" documentation and/or other materials provided with the distribution.11.\" 3. Neither the name of the University nor the names of its contributors12.\" may be used to endorse or promote products derived from this software13.\" without specific prior written permission.14.\"15.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND16.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE17.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE18.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE19.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL20.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS21.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)22.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT23.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY24.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF25.\" SUCH DAMAGE.26.\"27#include <sys/types.h>28#include <sys/socket.h>29#include <stdio.h>3031#define DATA1 "In Xanadu, did Kublai Khan . . ."32#define DATA2 "A stately pleasure dome decree . . ."3334/*35* This program creates a pair of connected sockets then forks and36* communicates over them. This is very similar to communication with pipes,37* however, socketpairs are two-way communications objects. Therefore I can38* send messages in both directions.39*/4041main()42{43int sockets[2], child;44char buf[1024];4546if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {47perror("opening stream socket pair");48exit(1);49}5051if ((child = fork()) == -1)52perror("fork");53else if (child) { /* This is the parent. */54close(sockets[0]);55if (read(sockets[1], buf, 1024, 0) < 0)56perror("reading stream message");57printf("-->%s\en", buf);58if (write(sockets[1], DATA2, sizeof(DATA2)) < 0)59perror("writing stream message");60close(sockets[1]);61} else { /* This is the child. */62close(sockets[1]);63if (write(sockets[0], DATA1, sizeof(DATA1)) < 0)64perror("writing stream message");65if (read(sockets[0], buf, 1024, 0) < 0)66perror("reading stream message");67printf("-->%s\en", buf);68close(sockets[0]);69}70}717273