【Linux】利用管道实现文件拷贝

管道:

我们把从一个进程连接到另一个进程的数据流称为一个管道;Linux下一切皆文件,所以管道也是一个文件。

在讲管道之前,我们先提一下涉及一点点其他的知识:

多进程看到一份公共的资源叫做临界资源;

  • 把访问临界资源的代码区域称为临界区;
  • 任何时候只有一个进程进入临界资源进行访问,并且在访问期间不允许其他的任何进程进入访问,称为互斥;
  • 在保证安全的情况下,进行访问临界资源的时候按照某种顺序,称为同步;
  • 一种事情要么做了,要么没做,不存在第三态,称为原子性。

管道分为两种:

匿名管道:

特点:

  1. 管道只允许单向通信
  2. 管道是自带互斥和同步的
  3. 匿名管道是只用于具有血缘关系的进程,常用于父子进程之间的通信
  4. 管道是面向字节流的
  5. 管道的生命周期随着通信双方的进程

创建方式:


#include <unistd.h> 

int pipe(int fd [2]);

fd是文件描述符组,其中fd[0]表示读端,fd[1]表示写端

返回值:成功返回0,失败返回错误代码


命名管道:

特点:

  1. 在匿名管道的基础上改变一条就行,命名管道不仅仅可使用在具有血缘关系的进程之间的通信,而且不具有血缘关系的进程之间也可以

创建方式:


命令行创建:

$ mkfifo namefifo


函数创建:

int mkfifo(const char *namefifo, mode_t mode)


两者管道的区别:

  • 匿名管道是用pipe创建的
  • 命名管道是由mkfifo函数创建,打开用open

例子:

用命名管道实现文件拷贝:

读取文件,写入命名管道:

  • read_pipe.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	mkfifo("fifo", 0644);
	int infd = open("file", O_RDONLY);
	if(infd == -1)
	{
		printf("open error!");
		exit(-1);
	}

	int outfd = open("fifo", O_WRONLY);
	if(outfd == -1)
	{
		printf("open error!");
		exit(-1);
	}

	char buf[1024];
	int n;
	while((n = read(infd, buf, 1024)) > 0)
	{
		//write(outfd, buf, strlen(buf));
		write(outfd, buf, n);
	}
	close(infd);
	close(outfd);

	return 0;
}

 读取管道,写入目标文件:

  • copy_pipe.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int outfd = open("file.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if(outfd == -1)
	{
		printf("open error!");
		exit(-1);
	}

	int infd = open("fifo", O_RDONLY);
	if(outfd == -1)
	{
		printf("open error!");
		exit(-1);
	}

	char buf[1024];
	int n;
	while((n = read(infd, buf, 1024)) > 0)
	{
	//	write(outfd, buf, strlen(buf));
		write(outfd, buf, n);
	}
	close(infd);
	close(outfd);
	unlink("fifo");

	return 0;
}
  • 注意:

先执行读入管道程序,再在另外一个终端执行拷贝程序,拷贝完成后会自动停止。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值