创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
int main(int argc,const char*argv[])
{
pid_t ID;
ID = fork();
if(ID==0)//ID等于零是属于子进程B
{
int fd1,fd2;
fd1 = open("1.txt",O_RDONLY);
fd2 = open("3.txt",O_WRONLY|O_TRUNC|O_CREAT,0664);
if(fd1==-1)
{
perror("open 1.txt");
return -1;
}
if(fd2==-1)
{
perror("open 3.txt");
return -1;
}
char buff[100];
int len = lseek(fd1,0,SEEK_END);
int len1,i=0;
lseek(fd1,0,SEEK_SET);
while(i<len/2)
{
len1=read(fd1,buff,1);
if(write(fd2,buff,1)!=len1)
{
perror("write");
close(fd1);
close(fd2);
return -1;
}
i++;
}
close(fd1);
close(fd2);
exit(EXIT_SUCCESS);
}
else if(ID>0)//ID>0属于父进程A
{
pid_t ID1;
ID1 = fork();//父进程创建子进程C
if(ID1==0)//子进程C
{
int fd1,fd2;
fd1 = open("1.txt",O_RDONLY);
usleep(1);
fd2 = open("3.txt",O_WRONLY|O_APPEND,0664);
if(fd1==-1)
{
perror("open 1.txt");
return -1;
}
if(fd2==-1)
{
perror("open 3.txt");
return -1;
}
char buff[100];
int len = lseek(fd1,0,SEEK_END);
int len1,i=0;
lseek(fd1,len/2,SEEK_SET);
while(i<len/2)
{
len1=read(fd1,buff,1);
if(write(fd2,buff,1)!=len1)
{
perror("write");
close(fd1);
close(fd2);
return -1;
}
i++;
}
close(fd1);
close(fd2);
exit(EXIT_SUCCESS);
}
if(ID1>0)//父进程A
{
wait(NULL);
wait(NULL);
sleep(3);
exit(EXIT_SUCCESS);
}
}
else
{
perror("fork");
return -1;
}
return 0;
}