创建三个进程,子进程1拷贝文件的前一半,子进程2拷贝文件的后一半,父进程回收两个子进程的资源
#include <myhead.h>
int main(int argc, const char *argv[])
{
//创建三个进程,子进程1拷贝文件的前一半,
//子进程2拷贝文件的后一半,父进程回收两个子进程的资源
int fd = open("./1.txt",O_RDONLY);
int len2;
if(fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
int len = lseek(fd,0,SEEK_END);
close(fd);
pid_t pid;
pid = fork();
if(pid ==0)//子进程1
{
int fd1,fd2;
fd1 = open("./1.txt",O_RDONLY);
fd2 = open("./2.txt",O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd1 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
if(fd2 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
char arr[10];
while(1)//文件信息读取
{
int len1;
len1 = read(fd1,arr,sizeof(arr));
len2 = lseek(fd1,0,SEEK_CUR);
write(fd2,arr,len1);
if(len/2-sizeof(arr)<len2)
{
read(fd1,arr,len/2-len2);
write(fd2,arr,len/2-len2);
break;
}
}
close(fd1);
close(fd2);
}
else if(pid > 0)
{
pid_t pid2;
pid2 = fork();
if(pid2 ==0)//子进程2
{
int fd1,fd3;
fd1 = open("./1.txt",O_RDONLY);
fd3 = open("./3.txt",O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd1 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
if(fd3 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
int len3;
char arr[10];
lseek(fd1,1*len/2,SEEK_SET);
while((len3 = read(fd1,arr,sizeof(arr)))>0)//后半段文件读取
{
write(fd3,arr,len3);
}
close(fd1);
close(fd3);
exit(EXIT_SUCCESS);
}
else if(pid2 > 0)//父进程
{
wait(NULL);
wait(NULL);
exit(EXIT_SUCCESS);
}
else
{
perror("fork");
exit(EXIT_SUCCESS);
}
}
else
{
perror("fork");
exit(EXIT_SUCCESS);
}
return 0;
}
创建三个进程,子进程1拷贝文件的前一半,子进程2拷贝文件的后一半,父进程回收两个子进程的资源(两半顺序颠倒)
#include <myhead.h>
int main(int argc, const char *argv[])
{
//创建三个进程,子进程1拷贝文件的前一半,
//子进程2拷贝文件的后一半,父进程回收两个子进程的资源
int fd = open("./1.txt",O_RDONLY);
int len2;
int fd4;
fd4 = open("./4.txt",O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd4 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
if(fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
int len = lseek(fd,0,SEEK_END);
close(fd);
pid_t pid;
pid = fork();
if(pid ==0)//子进程1
{
int fd1;
fd1 = open("./1.txt",O_RDONLY);
if(fd1 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
char arr[10];
while(1)//文件信息读取
{
int len1;
len1 = read(fd1,arr,sizeof(arr));
len2 = lseek(fd1,0,SEEK_CUR);
write(fd4,arr,len1);
if(len/2-sizeof(arr)<len2)
{
read(fd1,arr,len/2-len2);
write(fd4,arr,len/2-len2);
break;
}
}
close(fd1);
}
else if(pid > 0)
{
pid_t pid2;
pid2 = fork();
if(pid2 ==0)//子进程2
{
int fd1,fd3;
fd1 = open("./1.txt",O_RDONLY);
if(fd1 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
int len3;
char arr[10];
lseek(fd1,1*len/2,SEEK_SET);
while((len3 = read(fd1,arr,sizeof(arr)))>0)//后半段文件读取
{
write(fd4,arr,len3);
}
close(fd1);
exit(EXIT_SUCCESS);
}
else if(pid2 > 0)//父进程
{
wait(NULL);
usleep(2);
wait(NULL);
exit(EXIT_SUCCESS);
}
else
{
perror("fork");
exit(EXIT_SUCCESS);
}
}
else
{
perror("fork");
exit(EXIT_SUCCESS);
}
close(fd4);
return 0;
}
思维导图 进程
线程