拷贝一张图片

作业需求:

要去拷贝一张图片,子进程先拷贝后半部分,父进程再拷贝前半部分;可以使用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$ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值