The inter-process communication socketpair

socketpair is a way of inter-process communication.

API:

int socketpair(int domain, int type, int protocol, int sv[2]);

DEMO:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>

#define MAXLINE 4096

int main(int argc, char **argv) {
    int fd[2];
    pid_t pid;
    char line[MAXLINE];
    int n;
    
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
        perror("socketpair error");
        exit(1);
    }
    if ( (pid = fork()) < 0) {
        perror("fork error");
        exit(1);
    } else if (pid > 0) {
        close(fd[1]);
        write(fd[0], "hello world\n", 12);
        char tmp[MAXLINE];
        read(fd[0], tmp, MAXLINE);
        printf("echo is: %s\n", tmp);
    } else {
        close(fd[0]);
        n = read(fd[1], line, MAXLINE);
        write(STDOUT_FILENO, line, n);
        char tmp[] = "world says hi";
        write(fd[1], tmp, strlen(tmp));
    }
    exit(0);
}

And pipes and named pipes compared to, socketpair has the following characteristics:

1. Full-duplex

2 can be used between any two processes

Reproduced in: https: //www.cnblogs.com/gattaca/p/6548098.html

Guess you like

Origin blog.csdn.net/weixin_34236497/article/details/93519919