用有名管道实现文件复制,有两个终端 ,一个进行复制操作,另一个进行粘贴操作

这一段代码是进行复制操作,可以先将其生成可执行文件r,gcc - .xx.c -o r,便生成可执行文件r
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc, const char *argv[])
{
	int fd_fifo, fd_file;
	char buf[32] = {0};
	ssize_t s;

	if(mkfifo("./fifo", 0666) < 0)//创建管道
	{
		if(errno == EEXIST)//当管道文件已经存在不退出程序,继续执行
		{
			printf("fifo exist\n");
		}
		else
		{
			perror("fail to mkfifo");
			exit(1);
		}
	}
	fd_fifo = open("./fifo", O_WRONLY);//打开管道文件
	if(fd_fifo < 0)
	{
		perror("fail to open fifo");
		exit(1);
	}
	fd_file = open(argv[1], O_RDONLY);
	if(fd_file < 0)
	{
		perror("fail to open file");
		exit(1);
	}
	//读文件写管道
	while(1)
	{
		s = read(fd_file, buf, 32);
		if(s == 0)
			break;
		write(fd_fifo, buf, s);
	}

	return 0;
}
这段代码是进行 粘贴操作,先将其生成可执行文件w,gcc   xx.c   -o   w
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc, const char *argv[])
{
	int fd_fifo, fd_file;
	char buf[32] = {0};
	ssize_t s;

	if(mkfifo("./fifo", 0666) < 0)//创建管道
	{
		if(errno == EEXIST)//当管道文件已经存在不退出程序,继续执行
		{
			printf("fifo exist\n");
		}
		else
		{
			perror("fail to mkfifo");
			exit(1);
		}
	}
	fd_fifo = open("./fifo", O_RDONLY);//打开管道文件
	if(fd_fifo < 0)
	{
		perror("fail to open fifo");
		exit(1);
	}
	fd_file = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
	if(fd_file < 0)
	{
		perror("fail to open file");
		exit(1);
	}
//读管道写文件
	while(1)
	{
		s = read(fd_fifo, buf, 32);
		if(s == 0)
			break;
		write(fd_file, buf, s);
	}

	return 0;
}
生成这两个文件之后,打开两个终端,先执行 ./r 要复制的文件名 ,在另一个终端上执行./w  要复制成的文件名,就可以了。
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值