1、使用两个进程完成两个文件的拷贝,父进程拷贝前一半内容,子进程拷贝后一半内容,并且父进程要阻塞回收子进程资源
#include <myhead.h>
int main(int argc, const char *argv[])
{
char a[1] = {0};
pid_t pid;
pid = fork();//创建一个子进程
int src = open(argv[1],O_RDONLY);
if(src < 0)
{
perror("open error");
return -1;
}
int dest = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0666);
if(dest < 0)
{
perror("open error");
return -1;
}
//计算机读取文件的字符个数
int size = lseek(src,0,SEEK_END)-lseek(src,0,SEEK_SET);
int halfsize = size / 2;
ssize_t s;
//开始打印
if(pid < 0)
{
perror("fork error");
return -1;
}
else if(pid == 0)//子进程
{
lseek(src,1,SEEK_SET);
lseek(dest,1,SEEK_SET);
for(int i = 0; i<halfsize; i++)
{
s = read(src,a,1);
write(dest,a,s);
}
}
else//父进程
{
lseek(src,0,SEEK_SET);
lseek(dest,0,SEEK_SET);
for(int i = 0; i<halfsize; i++)
{
s = read(src,a,1);
write(dest,a,s);
}
//阻塞等待回收子进程资源
wait(NULL);
}
return 0;
}
2、使用三个进程完成两个文件的拷贝,父进程拷贝前三分之一,子进程1拷贝中间三分之一,子进程2拷贝后三分之一,父进程要阻塞回收所有子进程资源
#include <myhead.h>
int main(int argc, const char *argv[])
{
char a[1] = {0};
pid_t pid;
pid = fork();//创建一个子进程
int src = open(argv[1],O_RDONLY);
if(src < 0)
{
perror("open error");
return -1;
}
int dest = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0666);
if(dest < 0)
{
perror("open error");
return -1;
}
//计算机读取文件的字符个数
int size = lseek(src,0,SEEK_END)-lseek(src,0,SEEK_SET);
int len = size / 3;
ssize_t s;
//开始打印
if(pid < 0)
{
perror("fork error");
return -1;
}
else if(pid == 0)//子进程
{
lseek(src,1,SEEK_SET);
lseek(dest,1,SEEK_SET);
for(int i = 0; i<len; i++)
{
s = read(src,a,1);
write(dest,a,s);
}
}
else
{
pid_t pid2 = fork();//在父进程中再创建一个子进程
if(pid2 < 0)
{
perror("fork error");
return -1;
}
else if(pid2 == 0)
{
lseek(src,2,SEEK_SET);
lseek(dest,2,SEEK_SET);
for(int i = 0; i<len; i++)
{
s = read(src,a,1);
write(dest,a,s);
}
}
else//父进程
{
lseek(src,0,SEEK_SET);
lseek(dest,0,SEEK_SET);
for(int i = 0; i<len; i++)
{
s = read(src,a,1);
write(dest,a,s);
}
//阻塞等待回收子进程资源
wait(NULL);
wait(NULL);
}
}
return 0;
}
3、思维导图