How to use socketpair in the C language?

In C language, the socketpair function can be used to create a pair of interconnected sockets. These sockets can be used for communication within the same process. Here is how to use the socketpair function:

#include <sys/socket.h>

int socketpair(int domain, int type, int protocol, int sv[2]);
  1. Domain: specifies the protocol family (such as AF_UNIX or AF_INET).
  2. Specify the type of socket (such as SOCK_STREAM or SOCK_DGRAM).
  3. Protocol: Specifies the type of protocol (usually 0).
  4. An integer array used to store the file descriptors of a pair of sockets that have been created.

After calling the socketpair function, two interconnected sockets will be created that can be used for communication within the process. The first element of the sv array stores the file descriptor of the first socket, while the second element stores the file descriptor of the second socket.

Here is a simple example program demonstrating the use of the socketpair function.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

int main() {
    int sv[2];
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
        perror("socketpair");
        return 1;
    }

    char buf[256];
    if (fork() == 0) {
        close(sv[1]); // 关闭父进程的套接字
        read(sv[0], buf, sizeof(buf));
        printf("Child received message: %s\n", buf);
        close(sv[0]);
    } else {
        close(sv[0]); // 关闭子进程的套接字
        write(sv[1], "Hello from parent", 18);
        close(sv[1]);
    }

    return 0;
}

In the example above, a pair of sockets is first created using the socketpair function. Then a child process is created using the fork function, and communication is established between the parent and child processes. The parent process sends a message to the child process, which then prints it out upon receiving. Lastly, all socket file descriptors are closed.

bannerAds