IO线程学习day6

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

int main(int argc,const char*argv[])
{
	pid_t ID;
	ID = fork();
	if(ID==0)//ID等于零是属于子进程B
	{
		int fd1,fd2;
		fd1 = open("1.txt",O_RDONLY);
		fd2 = open("3.txt",O_WRONLY|O_TRUNC|O_CREAT,0664);

		if(fd1==-1)
		{
			perror("open 1.txt");
			return -1;
		}
		if(fd2==-1)
		{
			perror("open 3.txt");
			return -1;
		}
		char buff[100];
		int len = lseek(fd1,0,SEEK_END);
		int len1,i=0;
		lseek(fd1,0,SEEK_SET);
		while(i<len/2)
		{

			len1=read(fd1,buff,1);

			if(write(fd2,buff,1)!=len1)
			{
				perror("write");
				close(fd1);
				close(fd2);
				return -1;
			}
			i++;
		}
		close(fd1);
		close(fd2);

		exit(EXIT_SUCCESS);
	}
	else if(ID>0)//ID>0属于父进程A
	{
		pid_t ID1;
		ID1	= fork();//父进程创建子进程C
		if(ID1==0)//子进程C
		{
		int fd1,fd2;
		fd1 = open("1.txt",O_RDONLY);
		usleep(1);
		fd2 = open("3.txt",O_WRONLY|O_APPEND,0664);

		if(fd1==-1)
		{
			perror("open 1.txt");
			return -1;
		}
		if(fd2==-1)
		{
			perror("open 3.txt");
			return -1;
		}
		char buff[100];
		int len = lseek(fd1,0,SEEK_END);
		int len1,i=0;
		lseek(fd1,len/2,SEEK_SET);
		while(i<len/2)
		{

			len1=read(fd1,buff,1);
			if(write(fd2,buff,1)!=len1)
			{
				perror("write");
				close(fd1);
				close(fd2);
				return -1;
			}
			i++;
		}
		close(fd1);
		close(fd2);

		exit(EXIT_SUCCESS);
		}
		if(ID1>0)//父进程A
		{
			wait(NULL);
			wait(NULL);
			sleep(3);
			exit(EXIT_SUCCESS);
		}
	}
	else
	{
		perror("fork");
		return -1;
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值