Create a pair of connected sockets
#include <sys/types.h> #include <sys/socket.h> int socketpair( int domain, int type, int protocol, int * fd[2] );
libsocket
Use the -l socket option to qcc to link against this library.
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.
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 <sys/socket.h> #define CHAR_BUFSIZE 20 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, "First message"); write(fd[0], message, strlen(message) + 1); /* Print a message into the other end of the socket */ snprintf(message, CHAR_BUFSIZE, "Second message"); write(fd[1], message, strlen(message) + 1); /* Read back the data written to the first socket */ len = read(fd[0], message, CHAR_BUFSIZE-1); message[len] = '\0'; printf("Read [%s] from first fd \n", message); /* Read back the data written to the second socket */ len = read(fd[1], message, CHAR_BUFSIZE-1); message[len] = '\0'; printf("Read [%s] from second fd \n", message); close(fd[0]); close(fd[1]); return 0; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |