Updated: April 19, 2023 |
Create a pair of connected sockets
#include <sys/types.h> #include <sys/socket.h> int socketpair( int domain, int type, int protocol, int *fd );
The socketpair() call creates an unnamed pair of connected sockets in the specified domain, of the specified type, using the optionally specified protocol argument. The file descriptors are returned in the vector fd and are identical. Data that's written to one of the file descriptors can be read from the other.
Valid types are described in socket().
If the protocol argument is nonzero, it must be a protocol that's understood by the address family. No such protocols are defined at this time.
#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #define CHAR_BUFSIZE 50 int main(int argc, char **argv) { int fd[2], len; char message[CHAR_BUFSIZE]; if(socketpair(AF_LOCAL, SOCK_STREAM, 0, fd) == -1) { return 1; } /* If you write to fd[0], you read from fd[1], and vice versa. */ /* Print a message into one end of the socket. */ snprintf(message, CHAR_BUFSIZE, "A message written to fd[0]"); write(fd[0], message, strlen(message) + 1); /* Print a message into the other end of the socket. */ snprintf(message, CHAR_BUFSIZE, "A message written to fd[1]"); write(fd[1], message, strlen(message) + 1); /* Read from the first socket the data written to the second. */ len = read(fd[0], message, CHAR_BUFSIZE-1); message[len] = '\0'; printf("Read from fd[0]: %s \n", message); /* Read from the second socket the data written to the first. */ len = read(fd[1], message, CHAR_BUFSIZE-1); message[len] = '\0'; printf("Read from fd[1]: %s \n", message); close(fd[0]); close(fd[1]); return 0; }
This program produces the following output:
Read from fd[0]: A message written to fd[1] Read from fd[1]: A message written to fd[0]
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |