DAY5 IO进程

该程序使用C语言编写,通过创建父子进程来实现文件的拷贝。父进程和子进程分别处理文件的一半内容,从而协同完成整个文件的复制。首先打开源文件和目标文件,然后获取源文件的大小,接着创建子进程。子进程从文件中间开始读取并写入目标文件,而父进程则处理文件的前半部分。最后,父进程等待子进程结束并关闭文件。
摘要由CSDN通过智能技术生成

思维导图

 程序:使用父子进程完成文件的拷贝

#include<stdio.h>
#include<string.h>
#include<stdlib.h> 
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<sys/wait.h>
int main(int argc, const char *argv[])
{
	FILE *fpw,*fpr;//定义读写指针

	if((fpr=fopen("./4.c","r"))==NULL)
	{
		perror("fopen file");
		return -1;
	}
	if((fpw=fopen("./6.txt","w"))==NULL)
	{
		perror("fopen 6.txt");
		return -1;
	}
	//求文件大小
	fseek(fpr,0,SEEK_END);
	long int len=ftell(fpr);//838字节

	pid_t pid=fork();//创建子进程

	if(pid<0)
	{
		perror("folk error"); 
		return -1;
	}
	else if(pid==0) 
	{
		int count =len/2;
		printf("这是子进程pid=%d\n",getpid());
		fseek(fpr,count,SEEK_SET);
		fseek(fpw,count,SEEK_SET);
		char ch;

		for(int i=0;i<count;i++)
		{
			ch=fgetc(fpr);
			fputc(ch,fpw);
		}

		exit(EXIT_SUCCESS);
	}
	else
	{
		sleep(1);
		printf("这是父进程pid=%d\n",getpid());
		fseek(fpr,0,SEEK_SET);
		fseek(fpw,0,SEEK_SET);
		int count =len/2;
		char ch;

		for(int i=0;i<count;i++)
		{
			ch=fgetc(fpr);
			fputc(ch,fpw);
		}
		waitpid(pid,NULL,0);
	}

	fclose(fpr);
	fclose(fpw);
	return 0;
}

程序结果

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值