高级I/O函数之socketpair

pipe函数可用于创建一个管道,以实现进程间的通信。但是单个管道只能单向通信,一端用于读,一端用于写。若要实现双向通信,必须创建一对管道。而socketpair函数能够创建双向管道。

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

socketpair函数的前三个参数的含义与socket系统调用的三个参数完全相同。但domain只能使用本地域协议族,这是因为我们只能在本地创建双向管道。最后一个参数和pipe哈苏宁沪系统调用一样,只不过socketpair创建的这对文件描述符都是即可读又可写的。

socketpair函数成功时返回0,失败返回-1并设置errno。

/*************************************************************************
	> File Name: pair.c
	> Author: fucang_zxx
	> Mail: fucang_zxx@163.com 
	> Created Time: Thu 28 Jul 2016 03:27:24 PM CST
 ************************************************************************/

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

int main()
{
	int fd[2];
	//创建双向管道
	int ret = socketpair(AF_LOCAL, SOCK_STREAM, 0, fd);
	if(ret < 0)
	{
		perror("socketpair");
		return 1;
	}
	
	//创建子进程
	pid_t id = fork();
	if(id < 0)
	{
		//出错
		perror("fork");
		return 2;
	}
	else if(id == 0)
	{
		//child
		close(fd[0]);
		char buf[1024];
		while(1)
		{
			memset(buf, '\0', sizeof(buf));
			strcpy(buf, "hello father, i am child");
			write(fd[1], buf, strlen(buf));
			ssize_t _s = read(fd[1], buf, sizeof(buf) - 1);
			if(_s < 0)
			{
				perror("read");
				return 3;
			}
			else
			{
				buf[_s] = '\0';
				printf("father -> child:  %s\n", buf);
			}
			sleep(1);
		}
		close(fd[1]);
	}
	else
	{
		//father
		close(fd[1]);
		char buf[1025];
		while(1)
		{
			memset(buf, '\0', sizeof(buf));
			ssize_t _s = read(fd[0], buf, sizeof(buf) - 1);
			if(_s < 0)
			{
				perror("read");
				return 4;
			}
			else
			{
				buf[_s] = '\0';
				printf("child -> father:  %s\n", buf);
			}
			strcpy(buf, "hello child, i am father");
			write(fd[0], buf, strlen(buf));
			sleep(1);
		}
		close(fd[0]);
	}
	int status;
	waitpid(id, &status, WNOHANG);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值