#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//以读的方式打开源文件
int fd = open("./tu.png",O_RDONLY);
if (fd < 0)
{
perror("open");
return -1;
}
//以写的方式打开目标文件
int fd_w = open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC, 0664);
if (fd < 0)
{
perror("open");
return -1;
}
//文件大小
off_t size = lseek(fd, 0, SEEK_END);
//创建一个子进程
pid_t pid = fork(); //父子进程同时进行
//在父子进程中选择执行
if (pid>0)
{
//父进程运行
sleep(2);
//修改文件偏移量到0的位置
lseek(fd, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
char c = 0;
for(int i = 0; i<size/2; i++)
{
if(read(fd, &c, 1)<0)
{
perror("read");
return -1;
}
if(write(fd_w, &c, 1)<0)
{
perror("write");
printf("%d\n",__LINE__);
return -1;
}
}
printf("前半部分拷贝完毕\n");
}
else if (0==pid)
{
//子进程运行
//修改文件偏移量到size/2的位置
lseek(fd, size/2, SEEK_SET);
lseek(fd_w, size/2, SEEK_SET);
char c = 0;
for (int i=0; i<size/2; i++)
{
if(read(fd, &c, 1)<0)
{
perror("read");
return -1;
}
if(write(fd_w, &c, 1)<0)
{
perror("write");
return -1;
}
}
printf("后半部分拷贝完毕\n");
}
else if(pid<0)
{
perror("fork");
return -1;
}
//关闭文件
close(fd);
close(fd_w);
while(1)
{
sleep(1);
}
return 0;
}
ubuntu@ubuntu:io$ gcc 13test.c
ubuntu@ubuntu:io$ ./a.out
后半部分拷贝完毕
前半部分拷贝完毕
^C
ubuntu@ubuntu:io$ diff tu.png copy.png
ubuntu@ubuntu:io$