1> 使用两个进程完成两个文件的拷贝,父进程拷贝前一半内容,子进程拷贝后一半内容,并且父进程要阻塞回收子进程资源
#include <myhead.h>
int main(int argc, const char *argv[])
{
//终端输入两个文件名
if(argc!=3)
{
printf("input file error\n");
printf("usage:./a.out filename1 filename2\n");
return -1;
}
//fp复制源文件 fp1复制后的文件
FILE *fp;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp1;
if((fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
//创建父子进程
pid_t pid;
pid=fork();
if(pid<0)
{
perror("fork error");
return -1;
}else if(pid==0)
{
fseek(fp, 0, SEEK_END);
long int i=ftell(fp)/2;
fseek(fp,i,SEEK_SET);
char buf;
while((buf=fgetc(fp))!=EOF)
{
fputc(buf,fp1);
}
exit(EXIT_SUCCESS);
}else
{
fseek(fp, 0, SEEK_END);
long int i=ftell(fp)/2;
fseek(fp,0,SEEK_SET);
char buf;
while(ftell(fp)<i)
{
buf=fgetc(fp);
fputc(buf,fp1);
}
fflush(fp1);
exit(EXIT_SUCCESS);
wait(NULL);
}
fclose(fp);
fclose(fp1);
return 0;
}
2> 使用三个进程完成两个文件的拷贝,父进程拷贝前三分之一,子进程1拷贝中间三分之一,子进程2拷贝后三分之一,父进程要阻塞回收所有子进程资源
#include <myhead.h>
int main(int argc, const char *argv[])
{
//终端输入两个文件名
if(argc!=3)
{
printf("input file error\n");
printf("usage:./a.out filename1 filename2\n");
return -1;
}
//fp复制源文件 fp1复制后的文件
FILE *fp;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp1;
if((fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
//fp复制源文件 fp1复制后的文件
pid_t pid1;
pid1=fork();
fseek(fp1,0,SEEK_END);
if(pid1<0)
{
perror("fork error");
return -1;
}else if(pid1==0)//子进程1中间1/3
{
sleep(1);
fseek(fp, 0, SEEK_END);
long int i=ftell(fp)/3;
fseek(fp,i,SEEK_SET);
char buf;
while(ftell(fp)<i*2)
{
buf=fgetc(fp);
fputc(buf,fp1);
}
exit(EXIT_SUCCESS);
}else
{
pid_t pid2=fork();
if(pid2<0)
{
perror("fork error");
return -1;
}else if(pid2==0)//子进程2最后1/3
{
sleep(2);
fseek(fp, 0, SEEK_END);
long int i=ftell(fp)/3*2;
fseek(fp,i,SEEK_SET);
char buf;
while((buf=fgetc(fp))!=EOF)
{
fputc(buf,fp1);
}
exit(EXIT_SUCCESS);
}else//父进程第一个1/3
{
fseek(fp, 0, SEEK_END);
long int i=ftell(fp)/3;
fseek(fp,0,SEEK_SET);
char buf;
while(ftell(fp)<i)
{
buf=fgetc(fp);
fputc(buf,fp1);
}
fflush(fp1);
wait(NULL);
wait(NULL);
}
}
fclose(fp);
fclose(fp1);
return 0;
}
思维导图: