使用socketpair⽤来创建双向通信的管道


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

int main()
{
	pid_t pid;
	int fd[2];
	socketpair(AF_UNIX,SOCK_STREAM,0,fd);

	pid  = fork();
	if(pid < 0)
	{
		perror("fork");
		exit(1);
	}
	else if(pid == 0) //child
	{
		close(fd[0]);
		char *msg1 = "i am child";
		char buf1[512];
		while(1)
		{
			write(fd[1],msg1,strlen(msg1));
			ssize_t s = read(fd[1],buf1,sizeof(buf1) -1);
			buf1[s] = 0;  //因为这里不是从键盘中读入字符串,所以这里不需要s-1.
			printf("child say:%s\n",buf1);
		}

	}
	else //father
	{
		close(fd[1]);
		char *msg2 = "i am father";
		char buf2[512];
		while(1)
		{
			write(fd[0],msg2,strlen(msg2));
			ssize_t s = read(fd[0],buf2,sizeof(buf2) -1);
			buf2[s] = 0;  //因为这里不是从键盘中读入字符串,所以这里不需要s-1.
			printf("father say:%s\n",buf2);
		}

	}

	return 0;
}


截图:

从图中我们能看到父进程输出子进程的话,子进程输出父进程的话,可以证明这个管道是双向的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值