【操作系统】用命名管道实现一个简单的文件拷贝

【操作系统】Linux下进程间通信实现–匿名管道(PIPE),命名管道(FIFO)

程序源码:

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

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>



int main(int argc,char *argv[]){
    //创建命名管道
    mkfifo("tp",0644);
    //读端
    int infd;
    infd = open("abc",O_RDONLY);
    if(-1 == infd){
        perror("open");
        exit(1);
    }

    //写端
    int outfd;
    outfd = open("tp",O_WRONLY);
    if(-1 == outfd){
        perror("open");
        exit(1);
    }

    char buf[1024];
    int n;

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

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

    return 0;
}

fifo2file.c : (读取管道,写入目标文件abc.bak)

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>

int main(int argc,char *argv[]){
    //写端
    int outfd;
    outfd = open("abc.bak",O_WRONLY | O_CREAT | O_TRUNC,0644);
    if(-1 == outfd){
        perror("open");
        exit(1);
    }

    //读端
    int infd;
    infd = open("tp",O_RDONLY);
    if(-1 == infd){
        perror("open");
        exit(1);
    }

    char buf[1024];
    int n;
    //将从管道中读取到的数据写入文件abc.bak中
    while((n = read(infd,buf,1024))>0){
        write(outfd,buf,n);
    }

    close(infd);
    close(outfd);
    unlink("tp");
    return 0;
}

makefile:

.PHONY:all
all:fifo2file file2fifo


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

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

.PHONY:clean

clean:
    rm -f fifo2file file2fifo
程序运行结果:

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

这里写图片描述

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

这里写图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值