作业1、创建子父进程,子进程将1.txt内容拷贝到2.txt中,父进程将3.txt内容拷贝到4.txt中。
#include <myhead.h>int main(int argc, const char *argv[])
{//创建子父进程pid_t pid=fork();if(pid>0) //父进程{//打开文件1文件2int fd1=open("./1.txt",O_RDONLY);int fd2=open("./2.txt",O_CREAT|O_TRUNC|O_RDWR,0664);//拷贝int buff1[20];int res;while((res=read(fd1,buff1,sizeof(buff1)))>0){write(fd2,buff1,res);}//关闭文件close(fd1);close(fd2);}else if(pid==0) //子进程{//打开文件3文件4int fd3=open("./3.txt",O_RDONLY);int fd4=open("./4.txt",O_CREAT|O_TRUNC|O_RDWR,0664);//拷贝int buff1[20];int res;while((res=read(fd3,buff1,sizeof(buff1)))>0){write(fd4,buff1,res);}//关闭文件close(fd3);close(fd4);}else{perror("fork");}return 0;
}
作业2、创建子父进程,子进程拷贝文件的前一半,父进程拷贝后一半。
#include <myhead.h>int main(int argc, const char *argv[])
{//打开被拷贝文件和拷贝文件int fd1,fd2;fd1=open("./1.txt",O_RDONLY);fd2=open("./2.txt",O_CREAT|O_TRUNC|O_WRONLY,0664);if(-1==fd1||-1==fd2){perror("open");return -1;}int len=lseek(fd1,0,SEEK_END);//计算文件长度lseek(fd1,0,SEEK_SET);//将文件描述符回到开头char buff[500];int res,sum;//创建子父进程pid_t pid=fork();if(pid>0) //父进程拷贝文件前一半{while(1){res=read(fd1,buff,sizeof(buff));if((sum=lseek(fd1,0,SEEK_CUR))>=len/2){int k=lseek(fd1,-res,SEEK_CUR);res=read(fd1,buff,len/2-k);write(fd2,buff,res);break;}write(fd2,buff,res);} //关闭文件close(fd1);close(fd2);}else if(pid==0)//子进程拷贝文件后一半{usleep(1); //确保子进程后拷贝lseek(fd1,len/2,SEEK_SET); //将描述符放到文件中间lseek(fd2,len/2,SEEK_SET);while(res=read(fd1,buff,sizeof(buff))){write(fd2,buff,res);} //关闭文件close(fd1);close(fd2);}else{perror("fork");return -1;}return 0;
}
思维导图: