【Linux】使用命名管道实现简单的文件拷贝

在写代码之前,先介绍一个函数作为代码铺垫:

read函数理解:  ssize_t read(int fd, void *buf, size_t count);

fd:文件描述符,用来指向要操作的文件的文件结构体;

buf:一块内存空间;

count:希望读取的字节数.

具体实现代码如下:

makefile:

 .PHONY:all
 all : r_file r_fifo

 r_file : r_file.c
	  gcc - o $@ $ ^

 r_fifo : r_fifo.c
	  gcc - o $@ $ ^

.PHONY:clean
 clean :
	  rm - f r_file r_fifo

r_file.c : (读取文件file,写入命名管道)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 
#define MAX 1024
 
int main()
{
   mkfifo("fifo",0644);//创建命名管道

   //读端
  int infd;
  infd=open("file",O_RDONLY);//把file文件以只读方式打开
  if(infd==-1)//读取失败
   {
    perror("open");
   exit(1);
   }

  //写端
   int outfd;
   outfd=open("fifo",O_WRONLY);//把fifo以只写方式打开
   if(outfd==-1)
	  {
    perror("open");
     exit(1);
    }

  char buf[MAX];
  int s;
  while (s = (read(infd, buf, MAX))>0) 
	  //将文件描述符infd中的字节读取到缓冲区buf
	  //read返回成功读取到的字节数
  {
    write(outfd,buf,s);
	// write返回:若成功则返回写入的字节数,若出错则返回-1
	//write尝试将缓冲区buf中的字节写到文件描述符outfd中
   }

  close(infd);//关闭读端
  close(outfd);//关闭写端

   return 0;
 }

r_fifo.c : (读取管道,写入目标文件file.txt)

  #include <stdio.h>
  #include <stdlib.h>
  #include <unistd.h>
  #include <string.h>
  #include <sys/types.h>
  #include <sys/stat.h>
  #include <fcntl.h>
   
   #define MAX 1024
  
  int main()
  {
	  //写端
    int outfd;
    outfd=open("file.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);//让file.txt文件以写方式创建,并且 
 从文件的最开始去写
    if(outfd==-1)//创建失败时,则退出
   {
        perror("open");
        exit(1);
   }

	//读端
    int infd;
    infd=open("fifo",O_RDONLY);
    if(infd==-1)
    {
        perror("open");
        exit(1);
    }
   char buf[MAX];
   int s;

   //将从管道中读取到的数据写入文件file.txt中
   while ((s = read(infd, buf, MAX))>0) 
   {
     write(outfd,buf,s);
   }

   //关闭读写端
   close(infd);
   close(outfd);

    return 0;
  }

程序运行结果:

首先运行r_file,将文件file中的内容读取到管道中,然后进行进程等待:

 

然后运行r_fifo,将管道中的数据写入目标文件file.txt中,从而实现文件的拷贝:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值