①XMind
②双进程分工同时拷贝一个文件的上下两半部分
int main(int argc, const char *argv[])
{
int pid = -1;
//文件描述符创建(便于文件光标移动)
//①
int rfd = -1;
if( ( rfd = open("/root/fork2.c", O_RDONLY) ) == -1 )
{
perror("open error");
printf("行号:%d \n\n", __LINE__);
return -1;
}
int n = ( lseek(rfd,0,SEEK_END) - lseek(rfd,0,SEEK_SET) ) / 2;
//②
int wfd = -1;
if( ( wfd = open("/root/test.txt", O_WRONLY|O_CREAT|O_TRUNC, 0664) ) == -1 )
{
if( errno == EEXIST )
{
puts("文件已存在!");
printf("行号:%d \n\n", __LINE__);
wfd = open("/root/test.txt", O_WRONLY|O_TRUNC);
}
else
{
perror("open");
printf("行号:%d \n\n", __LINE__);
return -1;
}
}
//③
int rfd2;
if( (rfd2 = open("/root/fork2.c", O_RDONLY) ) == -1 )
{
perror("open error");
printf("行号:%d \n\n", __LINE__);
return -1;
}
//④
int wfd2 = -1;
if( ( wfd2 = open("/root/test.txt", O_WRONLY|O_CREAT|O_TRUNC, 0664) ) == -1 )
{
if( errno == EEXIST )
{
puts("文件已存在!");
printf("行号:%d \n\n", __LINE__);
wfd2 = open("/root/test.txt", O_WRONLY|O_TRUNC);
}
else
{
perror("open");
printf("行号:%d \n\n", __LINE__);
return -1;
}
}
char arr[10]="";
pid = fork();
if( pid>0 )
{
puts("父进程");
printf("行号:%d \n\n", __LINE__);
int pid2 = -1;
pid2 = fork();
if( pid2 == 0 )
{
puts("子进程② ");
printf("行号:%d \n\n", __LINE__);
lseek(rfd, 0, SEEK_SET);
lseek(wfd, 0, SEEK_SET);
while( n != lseek(rfd,0,SEEK_CUR) )
{
int m = read(rfd, arr, 1);
write(wfd, arr, m);
}
puts("子进程② 结束!");
printf("行号:%d \n\n", __LINE__);
exit(0);
}
}
else if( pid==0 )
{
puts("子进程① ");
printf("行号:%d \n\n", __LINE__);
lseek(rfd2, n, SEEK_SET);
lseek(wfd2, 0, SEEK_END);
while(1)
{
int m = read(rfd2,arr,1);
if( m == 0 )
{
printf("子进程① \n");
printf("行号:%d \n\n", __LINE__);
break;
}
write(wfd2, arr, m);
}
puts("子进程① 结束!");
printf("行号:%d \n\n", __LINE__);
exit(0);
}
close(rfd);
close(wfd);
wait(NULL);
wait(NULL);
puts("拷贝成功!!!");
return 0;
}