socketpair

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;
}
//总结:对于一个进程,当另一个进程往文件写入数据了,他才会会执行读操作。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值