socketpair

来源:互联网 发布:弘化社淘宝官方流通处 编辑:程序博客网 时间:2024/05/16 10:42

1.int socketpair(int domain, int type, int protocol, int fd[2]);

    //创建未命名的全双工管道,可以在一个主机上通信,也可以在网络上通信

domain(套接字的域):AF_LOCAL  用于在一个主机上通信

                                   AF_INET         用于在网络上通信

type:SOCK_STREAM  面向字节流

          SOCK_DGRAM   面向数据报

protocal(协议):默认为0

fd:用来存储文件描述符


实现:在一个主机上通信

#include<stdio.h>#include<sys/socket.h>#include<sys/types.h>#include<string.h>#include<stdlib.h>int main(){int fd[2];    if(socketpair(PF_LOCAL,SOCK_STREAM,0,fd)<0)  //创建双向通信管道,失败{perror("socketpair");}pid_t id=fork();if(id<0) //失败{perror("fork");}else if(id==0) //child    {close(fd[1]);while(1){char* msg="hello father,I am child";ssize_t s=write(fd[0],msg,strlen(msg)); //先写if(s<0)exit(1);    char buf[50];ssize_t r=read(fd[0],buf,50); //后读if(r<0)exit(2);else{buf[r]=0;}        printf("come father:%s\n",buf);}close(fd[0]);}else{close(fd[0]);while(1){sleep(4);    char buf[50];ssize_t r=read(fd[1],buf,50); //先读if(r<0)    return 1;else{buf[r]=0;}        printf("come child:%s\n",buf);char* msg="hello child,I am father..";ssize_t s=write(fd[1],msg,strlen(msg)); //后写if(s<0)return 2;}close(fd[1]);}return 0;}//总结:对于一个进程,当另一个进程往文件写入数据了,他才会会执行读操作。