使用有名管道在不同进程间复制文件

 复制端,打开文件,并将文件中数据
写入管道文件中

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define cpy "/tmp/cpy"

int main(int argc, char const *argv[])
{  
	ssize_t nread_file;
	ssize_t nwrite_fifo; 
    int i = 0;

	mkfifo(cpy,0777);
	/*创建有名管道*/
	int fd_fifo = open(cpy,O_RDWR);
	/*以可读可写打开有名管道*/
	int fd_file = open("1.pdf",O_RDWR);
	/*以可读可写打开文件*/
	char buf[1024] = {0};

	while(1)
	{
		memset(buf,0,sizeof(buf));
		 /*清空数组*/
		nread_file = read(fd_file,buf,sizeof(buf));
		/*读取文件*/
	    nwrite_fifo = write(fd_fifo,buf,nread_file);
	    /*将文件写入管道*/
	    if (nread_file<1024)
	    {/*如果读取少于1024,则到末尾,退出循环*/
	    	break;
	    }
	}
	printf("写入完成\n");
	
	return 0;
}

粘贴端,打开管道,并将管道中数据
写入目标文件中

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define cpy "/tmp/cpy"

int main(int argc, char const *argv[])
{  
	ssize_t nread_fifo; 
	ssize_t nwrite_file;
    int i = 0;

	mkfifo(cpy,0777);
	/*创建有名管道*/
	int fd_fifo = open(cpy,O_RDWR);
	/*以可读可写打开有名管道*/
	int fd_file_p = open("2.pdf",O_RDWR|O_CREAT,0777);
	/*以可读可写打开文件,如果文件不存在则创建文件*/
	char buf[1024] = {0};

	while(1)
	{
		memset(buf,0,sizeof(buf));
	    /*清空数组*/
	    nread_fifo = read(fd_fifo,buf,sizeof(buf));
	    /*从管道中读取数据*/
	    nwrite_file = write(fd_file_p,buf,nread_fifo);
	    /*将数据写入新的文件中*/
	    if (nread_fifo < 1024)
		{/*如果读取少于1024,则到末尾,退出循环*/
			break;
		}
	    i++;
	}
	printf("复制完成\n");
	printf("一共复制%d次,共计%d字节\n",i,i*1024);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42723835/article/details/81586578