进程间通信之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. 可用于任意两个进程之间的通信

posted @ 2017-03-14 13:48  Sawyer Ford  阅读(2526)  评论(0编辑  收藏  举报