通过有名管道实现简单的文件传输

写函数write.c:

#include
#include
#include
#include
#include
#include
#include

#define N 32
#define FIFOPATH "/home/linux/gz18031/io/day05/trans/myfifo"       //定义管道路径宏

int main(int argc, const char *argv[])
{
	if(argc != 2)                    //参数个数判断,传参不正确将退出
	{
		printf("cmd + srcfile\n");
		return -1;
	}
	int fd_fifo,fd_src,ret;       //
	char buf[N] = {};

	if(mkfifo(FIFOPATH,0666) != 0)      //创建管道
	{
		if(errno != EEXIST)   //假如错误不是“已存在管道”,则退出
		{
			perror("fail to mkfifo");
			return -1;
		}
	}

	fd_src = open(argv[1],O_RDONLY);          //只读方式打开要传输的文件
	if(fd_src < 0)
	{
		perror("fail to open");
		return -1;
	}

	fd_fifo = open(FIFOPATH,O_WRONLY);     //只写方式打开管道
	if(fd_fifo < 0)
	{
		perror("fail to open");
		return -1;
	}

	write(fd_fifo,argv[1],N);            //向管道写入要传输文件的文件名
	while(1)
	{
		ret = read(fd_src,buf,N);      //从要传输的文件中读取N个字符到buf
		if(ret == 0)                  //若从传输文件读取完毕,则退出循环
		{
			break;
		}
		write(fd_fifo,buf,ret);          //将buf中的ret个字符写入管道
	}
	close(fd_fifo);
	close(fd_src);

	
	return 0;
}

 读函数read.c:

#include
#include
#include
#include
#include
#include
#include

#define N 32
#define FIFOPATH "/home/linux/gz18031/io/day05/trans/myfifo"

int main(int argc, const char *argv[])
{
	int fd_fifo,fd_dest,ret;
	char buf[N] = {};

	if(mkfifo(FIFOPATH,0666) != 0)
	{
		if(errno != EEXIST)
		{
			perror("fail to mkfifo");
			return -1;
		}
	}

	fd_fifo = open(FIFOPATH,O_RDONLY);   //只读方式打开管道
	if(fd_fifo < 0)
	{
		perror("fail to open");
		return -1;
	}

	read(fd_fifo,buf,N);              //从管道读取N个字符到buf

	fd_dest = open(buf,O_WRONLY|O_CREAT|O_TRUNC,0666);        //创建与传输文件同文件名的文件,并打开
	if(fd_dest < 0)
	{
		perror("fail to oepn");
		return -1;
	}

	while(1)
	{
		ret = read(fd_fifo,buf,N);                       //从管道读取N个字符到buf
		if(ret == 0)                                 //读取完毕,则退出
		{
			break;
		}
		write(fd_dest,buf,ret);                 //向新创建的文件写入buf实际读取到的字符
	}

	close(fd_fifo);
	close(fd_dest);

	
	return 0;
}

你可能感兴趣的:(通过有名管道实现简单的文件传输)