代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int p1 = open("1.png",O_RDONLY);
if(p1<0)
{
perror("open");
return -1;
}
int p2 = open("2.png",O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(p2<0)
{
perror("open");
return -1;
}
//文件大小
off_t sum = lseek(p1,0,SEEK_END);
pid_t pid = fork();
//父进程
if(pid>0)
{
sleep(1);
lseek(p1,0,SEEK_SET);
lseek(p2,0,SEEK_SET);
char c=0;
for(int i=0;i<sum/2;i++)
{
if(read(p1,&c,1)<0)
{
perror("read");
return -1;
}
if(write(p2,&c,1)<0)
{
perror("read");
return -1;
}
}
}
//子进程
else if(pid == 0)
{
lseek(p1,sum/2,SEEK_SET);
lseek(p2,sum/2,SEEK_SET);
char c=0;
for(int i=0;i<sum/2;i++)
{
if(read(p1,&c,1)<0)
{
perror("read");
return -1;
}
if(write(p2,&c,1)<0)
{
perror("read");
return -1;
}
}
}
else
{
perror("fork");
return -1;
}
close(p1);
close(p2);
return 0;
}
结果如下:
ubuntu@ubuntu:day4$ diff 1.png 2.png
ubuntu@ubuntu:day4$