这一段代码是进行复制操作,可以先将其生成可执行文件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 要复制成的文件名,就可以了。