進程間通信之socketpair


socketpair是進程間通信的一種方式。

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);
}

管道命名管道相比,socketpair有以下特點:

1. 全雙工

2. 可用於任意兩個進程之間的通信


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM