IO作业day5
作业:创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid1,pid2;
pid1 = fork();
int sum = 0;
FILE *fp = fopen("./1.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
fseek(fp,0,SEEK_END);//移动到文件末尾
int len = ftell(fp);
fclose(fp);
if(pid1>0)//父进程
{
pid2 = fork();
if(pid2>0)//父进程
{
waitpid(-1,NULL,0);//阻塞回收子进程资源
printf("成功回收子进程资源\n");
waitpid(-1,NULL,0);
printf("成功回收子进程资源\n");
}
else if(pid2 == 0)//二儿子进程
{
fp = fopen("./1.txt","r");
FILE *fp3 = fopen("./3.txt","w");
if(fp3 == NULL)
{
perror("fopen");
return -1;
}
fseek(fp,len/2,SEEK_SET);
char buff[5];
while(1)
{
int res = fread(buff,1,sizeof(buff),fp);
if(res <= 0)
{
break;
}
fwrite(buff,1,res,fp3);
}
fclose(fp);
fclose(fp3);
exit(0);
}
else
{
perror("fork");
return -1;
}
}
else if(pid1 == 0)//大儿子进程
{
fp = fopen("./1.txt","r");
FILE *fp2 = fopen("./2.txt","w");
if(fp2 == NULL)
{
perror("fopen");
return -1;
}
char buff[5];
while(sum<len/2)
{
int res = fread(buff,1,sizeof(buff),fp);
sum += res;
int k = res;
if(sum > len/2)
{
k = res - (sum - len/2);
}
fwrite(buff,1,k,fp2);
}
fclose(fp2);
fclose(fp);
exit(0);
}
return 0;
}
xmind
原文地址:https://blog.csdn.net/JOUzb/article/details/143694112
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!