//把源文件中的数据读入到管道文件中
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int do_copy(int fd_s,int fd_d)
{
char buf[1024] = {0};
int ret = 0;
while((ret = read(fd_s,buf,sizeof(buf))) != 0)
write(fd_d,buf,ret);
return 0;
}
//./a.out src fifo
int main(int argc, const char *argv[])
{
int fd_s;
int fd_d;
//1.命令行参数的处理
if(argc != 3)
{
printf("Usage: %s src fifo\n",argv[0]);
exit(EXIT_FAILURE);
}
//创建有名管道
if(mkfifo(argv[2],0666) < 0 && errno != EEXIST)
{
perror("mkfifo fail");
exit(EXIT_FAILURE);
}
//后面文件的操作
//1.打开 --- open
//2.读写 --- read 、write
//3.关闭 close
//1.打开文件
fd_s = open(argv[1],O_RDONLY);
if(fd_s < 0)
{
perror("open fail");
exit(EXIT_FAILURE);
}
//目标文件是"管道文件" 此处对目标文件的操作是 只写方式
fd_d = open(argv[2],O_WRONLY);
//fd_d = open(argv[2],O_RDWR);
if(fd_d < 0)
{
perror("open fail");
exit(EXIT_FAILURE);
}
printf("write file\n");
//2.读写
do_copy(fd_s,fd_d);
//3.关闭
close(fd_s);
close(fd_d);
return 0;
}
从有名管道中获取数据写入到目标文件
#include <stdio.h>
#include <stdlib.h>#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int do_copy(int fd_s,int fd_d)
{
char buf[1024] = {0};
int ret = 0;
while((ret = read(fd_s,buf,sizeof(buf))) != 0)
{
printf("ret = %d\n",ret);
write(fd_d,buf,ret);
}
printf("read ret = %d\n",ret);
return 0;
}
//./a.out fifo dest
int main(int argc, const char *argv[])
{
int fd_s;
int fd_d;
//1.命令行参数的处理
if(argc != 3)
{
printf("Usage: %s fifo dest\n",argv[0]);
exit(EXIT_FAILURE);
}
if(mkfifo(argv[1],0666) < 0 && errno != EEXIST)
{
perror("mkfifo fail");
exit(EXIT_FAILURE);
}
//后面文件的操作
//1.打开 --- open
//2.读写 --- read 、write
//3.关闭 close
//1.打开文件 --- 源文件是管道文件 ,此处对管道文件的操作方式是 ,只读的
fd_s = open(argv[1],O_RDONLY);
// fd_s = open(argv[1],O_RDWR);
if(fd_s < 0)
{
perror("open fail");
exit(EXIT_FAILURE);
}
//目标文件
fd_d = open(argv[2],O_WRONLY|O_TRUNC|O_CREAT,0666);
if(fd_d < 0)
{
perror("open fail");
exit(EXIT_FAILURE);
}
//2.读写
do_copy(fd_s,fd_d);
//3.关闭
close(fd_s);
close(fd_d);
return 0;
}
一端用只读或是只写方式打开,运行程序时,程序阻塞在打开操作!直到另一端用相对的方式(只写或只读)方式打开时,程序才会解除阻塞继续往下执行!