利用fork(创建子进程)函数拷贝一张图片,子进程先拷贝后半部分,父进程再拷贝前半部分;可以使用sleep函数

代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
	int fd = open("./1.png",O_RDONLY);
	if(fd < 0)
	{
		perror("open");
		return -1;
	}
	int fd1 = open("./2.png",O_RDWR|O_CREAT|O_TRUNC,0664);
	if(fd1 < 0)
	{
		perror("open");
		return -1;
	}
	off_t size = lseek(fd,0,SEEK_END);//通过偏移计算文件大小
    char str[120] = "";//用来存放读取的内容
    ssize_t res;//从读取文件获取的字节数
	int count = 0;//用来计算输入的字节个数 
	pid_t pid = fork();//开启子进程
	if(pid == 0)//子进程运行
	{      
		lseek(fd,size/2,SEEK_SET);//将光标偏移到读取的文件一半处
		lseek(fd1,size/2,SEEK_SET);//将光标偏移到复制的文件一半处
		while(1)
		{
			res = read(fd,str,sizeof(str));
            if(res == 0)
			{
               break;
			}
			else if(res < 0)
			{
				perror("read");
				return -1;
			}
			res = write(fd1,str,res);
		    if(res < 0)
			{
                perror("write");
				return -1;
			}
		}
	}
	else if(pid > 0)//父进程运行
	{
		sleep(1);
		lseek(fd,0,SEEK_SET);//将光标偏移到读取文件的开头
		lseek(fd1,0,SEEK_SET);//将光标偏移到复制文件的开头
		while(1)
		{
			res = read(fd,str,sizeof(str));
            if(res < 0)
			{
				perror("read");
				return -1;
			}
			count = count + res;
			if(count <= size/2)//如果读取的内容超过读取文件的一半将退出读写
			    res = write(fd1,str,res);
            else
			{
				res = write(fd1,str,res-(count-size/2));
			    break;
			}
		    if(res < 0)
			{
                perror("write");
				return -1;
			}	
		}
	}
	close(fd);
	close(fd1);
	return 0;
}

1.让父进程晚于子进程运行只需要在父进程运行的前面加上sleep函数来推迟父进程的运行

2.在父进程中需要复制文件的前半部分,需要考虑在文件中间部分读写时的字节数与退出条件,需要把文件前半部分数组未读写完的部分读写出来,而抛弃数组读取到的文件后半部分的内容。

实现效果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值