linux 进程间通信,使用socketpair,pipe

管道pipe是半双工的,pipe两次才能实现全双工,使得代码复杂。socketpair直接就可以实现全双工

socketpair对两个文件描述符中的任何一个都可读和可写,而pipe是一个读,一个写

1,使用socketpair,实现进程间通信,是双向的。

2,使用pipe,实现进程间通信

使用pipe关键点:fd[0]只能用于接收,fd[1]只能用于发送,是单向的。

3,使用pipe,用标准输入往里写。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <wait.h>

int main(){
  int sv[2];
  pid_t pid;
  char buf[128];

  memset(buf, 0, sizeof(buf));

  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0){
    perror("socketpair");
    return 1;
  }

  pid = fork();
  if(pid < 0){
    perror("fork");
    return 1;
  }
  if(pid == 0){
    close(sv[0]);
    read(sv[1], buf, sizeof(buf));
    printf("child process : data from parant process [%s]
", buf);
    exit(0);
  }
  else {
    int status;
    close(sv[1]);
    write(sv[0], "HELLO", 5);
    printf("parent process : child process id %d
", pid);
    wait(&status);
  }

  return 0;
}

使用pipe,做全双工

#include <stdlib.h>  
#include <stdio.h>  
  
int main ()  
{  
    int fd1[2],fd2[2];  
    pipe(fd1);  
    pipe(fd2);  
    if ( fork() ) {  
        /* Parent process: echo client */  
        int val = 0;  
        close( fd1[0] );  
        close(fd2[1]);  
        while ( 1 ) {  
            sleep( 1 );  
            ++val;  
            printf( "parent Sending data: %d
", val );  
            write( fd1[1], &val, sizeof(val) );  
            read( fd2[0], &val, sizeof(val) );  
            printf( "parent Data received: %d
", val );  
        }  
    }  
    else {  
        /* Child process: echo server */  
        int val ;  
        close( fd1[1] );  
        close(fd2[0]);  
        while ( 1 ) {  
            read( fd1[0], &val, sizeof(val) );  
            printf( "son Data received: %d
", val );  
            ++val;  
            write( fd2[1], &val, sizeof(val) );  
            printf( "son send received: %d
", val );  
        }  
    }  
}  
原文地址:https://www.cnblogs.com/wangshaowei/p/12733260.html