作业需求:
要去拷贝一张图片,子进程先拷贝后半部分,父进程再拷贝前半部分;可以使用sleep函数
实现过程:
一段一段的复制
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
int dp=open("./2.png",O_RDONLY);
int dp1=open("./cp.png",O_RDWR|O_CREAT|O_TRUNC,0777);
if(dp<0 || dp1<0)
{
printf("复制失败\n");
return-1;
}
char str[20]="";
char str1[20]="";
ssize_t res,res1;
struct stat buf;
stat("./2.png",&buf);
off_t t=(buf.st_size/2);
pid_t pid=fork();
if(pid>0)
{
sleep(1);
int flag=0;
lseek(dp,0,SEEK_SET);
lseek(dp1,0,SEEK_SET);
while(1)
{
bzero(str,sizeof(str));
res1=t/(sizeof(str))==0 ? t:sizeof(str);
res=read(dp,str,sizeof(str));
t=t-res1;
if(res<0)
{
perror("read");
}
write(dp1,str,res);
flag=flag+res1;
if(flag==(buf.st_size)/2)
{
printf("1\n");
break;
}
}
printf("父进程结束\n");
}
else if (0==pid)
{
lseek(dp,buf.st_size/2,SEEK_SET);
lseek(dp1,buf.st_size/2,SEEK_SET);
while(1)
{
bzero(str,sizeof(str));
res=read(dp,str,sizeof(str)-1);
if(res==0)
{
printf("2");
break;
}else if(res<0)
{
perror("read");
}
res1=write(dp1,str,res);
if(res1<0)
{
perror("write");
}
}
printf("子进程结束\n");
}
return 0;
}
实现结果:
ubuntu@ubuntu:04_day$ gcc cp.c
ubuntu@ubuntu:04_day$ ./a.out
2子进程结束
1
父进程结束
ubuntu@ubuntu:04_day$ diff cp.png 2.png
ubuntu@ubuntu:04_day$
实现过程:
一个一个的复制
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
int fp=open("./2.png",O_RDONLY);
int fp1=open("./cp.png",O_RDWR|O_CREAT|O_TRUNC);
if(fp<0 || fp1<0)
{
perror("open");
return -1;
}
off_t size=lseek(fp,0,SEEK_END)/2;
char c;
pid_t pid=fork();
ssize_t res;
if(pid>0)
{
sleep(1);
lseek(fp,0,SEEK_SET);
lseek(fp1,0,SEEK_SET);
for(int i=0;i<size;i++)
{
res=read(fp,&c,1);
if(res<0)
{
perror("read");
return -1;
}
write(fp1,&c,1);
}
printf("前半段复制成功\n");
}
else if(pid==0)
{
lseek(fp,size,SEEK_SET);
lseek(fp1,size,SEEK_SET);
for(int i=0;i<size;i++)
{
res=read(fp,&c,1);
if(res<0)
{
perror("read");
return -1;
}
write(fp1,&c,1);
}
printf("后半段复制成功\n");
}
close(fp);
close(fp1);
return 0;
}
实现结果:
ubuntu@ubuntu:04_day$ gcc cp2.c
ubuntu@ubuntu:04_day$ ./a.out
后半段复制成功
前半段复制成功
ubuntu@ubuntu:04_day$ diff cp.png 2.png
ubuntu@ubuntu:04_day$