思维导图
程序:使用父子进程完成文件的拷贝
#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;
}
程序结果