天天看點

socketpair

pipe用來建立管道,但是單個管道隻能進行單向通信,一頓用于讀,一段用于寫,如果要實作程序雙向通信,必須建立一對管道。

而socketpair則可以用來建立雙向通信的管道具體實作如下:

實作,打開的還是一個檔案,fd[0],fd[1],管道中f[0]讀端,f[1]寫端。

#include <sys/types.h>   

#include <sys/socket.h>

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

domain:選用AF_LOCAL;

type:SOCK_STREAM

protocol:預設0

socketpair
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>

int main()
{
  int fd[2];
  if(socketpair(AF_LOCAL,SOCK_STREAM,0,fd)<0){
    perror("sockpair");
    return 1;
  }
  pid_t id=fork();
  if(id<0){
    perror("fork");
    return 2;
  }
  else if(id==0)
  {
    close(fd[0]);
    char buf[1024];
    while(1)
    {
      strcpy(buf,"hello world");
      write(fd[1],buf,strlen(buf));
      ssize_t _s=read(fd[1],buf,sizeof(buf)-1);
      buf[_s]='\0';
      printf("father->child:%s\n",buf);
      sleep(1);
    }
    close(fd[1]);
  }
  else
  {
    close(fd[1]);
    char buf[1024];
    while(1)
    {
      ssize_t _s=read(fd[0],buf,sizeof(buf)-1);
      if(_s>0)
      {
        buf[_s]='\0';
        printf("child->father:%s\n",buf);
        sleep(1);
      }
      strcpy(buf,"hello mygirl");
      write(fd[0],buf,strlen(buf));
    }
    close(fd[0]);

  }
  return 0;
}