【实验三】Linux的匿名管道的编程

这篇博客详细介绍了匿名管道在父子进程间通信的实现,通过示例代码展示了如何创建匿名管道、定义客户端和服务端的功能,并给出了编译与运行的步骤。读者可以了解到如何使用C++进行简单的进程间通信操作。

目录

一、匿名管道具体介绍

二、代码实现

1、mypipes.cpp

2、server.h

3、server.cpp

4、client.h

5、client.cpp

6、pipe.mk

三、运行结果


一、匿名管道具体介绍

管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用,进程的亲缘关系通常是指父子进程关系。

参考博客

二、代码实现

1、mypipes.cpp

#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include"client.h"
#include"server.h"
int main(int argc,char* argv[]){
	int fd[2];
	int fd1[2];
        pipe(fd);
        pipe(fd1);
	pid_t child=fork();
	if(child==0){ 
		close(fd[0]);
		close(fd1[1]);
		client(fd[1],fd1[0]);
		close(fd[1]);
		close(fd1[0]);
		exit(0);
	}else{ 
   		close(fd[1]);
		close(fd1[0]);
		server(fd[0],fd1[1]);
		close(fd[0]);
		close(fd1[1]);
		wait(NULL);
	}
	return 0;
}

2、server.h

void server(const int rfd1,int wfd2);

3、server.cpp

#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include"server.h"

const int LEN=4096;

void server(const int rfd1,const int wfd2){
	char buf[LEN]={'\0'};
	int len=read(rfd1,buf,LEN-1);
	buf[len]='\0';
	int fd=open(buf,O_RDONLY);
	if(fd==-1){
	     char buf1[]="don't open file";
	     write(wfd2,buf1,strlen(buf1));
	}else{
      	 while((len=read(fd,buf,LEN-1))>0){
       		buf[LEN]='\0';
		write(wfd2,buf,strlen(buf));
           }
	}
       close(fd);
}

4、client.h

void client(const int wfd1,const int rfd2);

5、client.cpp

#include<iostream>
#include<unistd.h>
#include<string.h>
#include"client.h"

const int LEN=4096;

void client(const int wfd1,const int rfd2){
	char buf[LEN]={'\0'};
	std::cout<<"please enter file name:";
	std::cin>>buf;
	write(wfd1,buf,strlen(buf));
	int len=0;
	while((len=read(rfd2,buf,LEN-1))>0){
		buf[LEN]='\0';
		std::cout<<buf<<std::endl;
	}
	
}

6、pipe.mk

GCC=g++
CFLAG=-c
OFLAG=-o
OBJ=mypipes.o server.o client.o
EXE=mypipes
${EXE}:${OBJ}
        ${GCC} ${OFLAG} $@ $^
%.o:%.cpp
        ${GCC} ${CFLAG} $^
clean:
        rm *.o
              
mypipes:mypipe.o server.o client.o
        g++ -o mypipes mypipes.o server.o client.o
mypipes.o:mypipes.cpp
        g++ -c mypipes.cpp
server.o:server.cpp
        g++ -c server.cpp
client.o:client.cpp
        g++ -c client.cpp
clean:
        rm *.o

三、运行结果

2b6fd4a15d3c47f1bb781d10bd4c79dd.png

255a9a95f6094d10b608c9aba0e48a34.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值