8.26每日作业

创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。  

#include <myhead.h>

int main(int argc, const char *argv[])
{
	/*
	创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。 
	*/
	pid_t pid;
	pid = fork();
	int len;	
	if(pid == 0)
	{
#if 1
		int fd,fd1;
		fd = open("./1.txt",O_RDONLY);
		fd1 = open("./2.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
		if(fd==-1)
		{
			perror("open");
			return -1;
		}
		if(fd1==-1)
		{
			perror("open");
			return -1;
		}
		len = lseek(fd,0,SEEK_END);
		int t = len/2;
		if(t%2 != 0)
		{
			t++;
		}
		lseek(fd,0,SEEK_SET);
		char s[5];
		read(fd,s,t);
		write(fd1,s,t);

		close(fd);
		close(fd1);
#endif
		exit(0);
	}
	else if(pid > 0)
	{
		pid_t pid2;
		pid2 = fork();
		if(pid2 == 0)
		{
			sleep(2);
			int fd,fd1;
			fd = open("./1.txt",O_RDONLY);
			fd1 = open("./2.txt",O_WRONLY|O_CREAT|O_APPEND,0664);
			if(fd==-1)
			{
				perror("open");
				return -1;
			}
			if(fd1==-1)
			{
				perror("open");
				return -1;
			}
			len = lseek(fd,0,SEEK_END);
			int t = len/2;
			if(t%2 != 0)
			{
				t++;
			}
			lseek(fd,t,SEEK_SET);
			lseek(fd1,0,SEEK_END);
			char s[5];
			read(fd,s,t);
			write(fd1,s,t);

			close(fd);
			close(fd1);
			exit(0);
		}
		else if(pid2 > 0)
		{
			sleep(4);
			int fd,fd1;
			fd = open("./1.txt",O_RDONLY);
			fd1 = open("./2.txt",O_RDONLY);
			len = lseek(fd,0,SEEK_END);
			if(fd1==-1)
			{
				perror("open");
				return -1;
			}
			char buf[102400];
			lseek(fd1,0,SEEK_SET);
			read(fd1,buf,len);
			printf("%s\n",buf);

			close(fd);
			close(fd1);
	
			wait(NULL);
			wait(NULL);
			usleep(3);


			exit(0);
		}
	}
	else
	{
		perror("fork");
		exit(1);
	}
	return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值