利用两个进程实现cp复制功能
利用有名管道,一个进程读取复制文件,写到管道中,一个进程读取管道中的内容,写到目标文件中。
第一部分,读取内容写到管道中。
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
// 从文件中读取数据,写到管道中
// 创建管道文件,并打开(只写)
// 只读打开要被复制的文件
// 循环从文件中读取,并写到管道中
int main(int argc, char const *argv[])
{
// 输入格式
if (argc != 2)
{
printf("format: %s <filename>\n", argv[0]);
return -1;
}
int fd1, fd2;
char buf[32] = "";
ssize_t num;
// 创建管道文件
int n;
n = mkfifo("fifo", 0666);
// 判断管道文件是否创建成功
if (n < 0)
{
// 如果错误号errno为EEXIST则代表管道文件已存在
// 如果管道文件已存在,则打印句提示语句而不是走到return -1
if (errno == EEXIST)
{
printf("file exist\n");
}
else
{
perror("mkfifo err");
return -1;
}
}
printf("mkfifo success\n");
// 打开管道文件
fd1 = open("fifo", O_WRONLY);
if (fd1 < 0)
{
perror("fifo open error");
return -1;
}
// 打开要复制的文件
fd2 = open(argv[1], O_RDONLY);
if (fd2 < 0)
{
perror("open file error");
return -1;
}
// 读写操作
// 只要读到数据,就写到管道里
while ((num = read(fd2, buf, 32)) > 0)
{
write(fd1, buf, num);
sleep(1);
}
// 关闭文件描述符
close(fd1);
close(fd2);
return 0;
}
第二部分。读取管道中的内容写到目标文件中
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
// 从管道中读取数据,写到目标文件中
// 打开管道文件(只读)
// 只写打开要被复制的文件
// 循环从管道中读取,并写到目标文件中
int main(int argc, char const *argv[])
{
// 输入格式
if (argc != 2)
{
printf("format: %s <filename>\n", argv[0]);
return -1;
}
// 定义文件描述符
int fd1, fd2;
// 暂存读写的数据
char buf[32] = "";
ssize_t num;
// 打开管道文件
fd1 = open("fifo", O_RDONLY);
if (fd1 < 0)
{
perror("fifo open error");
return -1;
}
// 打开目标文件
fd2 = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd2 < 0)
{
perror("open file error");
return -1;
}
// 读写操作
// 只要从管道中读到数据,就写到目标文件中
while ((num = read(fd1, buf, 32)) > 0)
{
write(fd2, buf, num);
sleep(1);
}
// 关闭文件描述符
close(fd1);
close(fd2);
return 0;
}