作业
创建3个进程,子进程1拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
将1.txt内容拷贝到2.txt中
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid1;
pid1 = fork();
int fd1 = open("./1.txt",O_RDWR);
if(fd1==-1)
{
perror("open");
return -1;
}
int fd2 = open("./1.txt",O_RDWR);
if(fd2==-1)
{
perror("open");
return -1;
}
int fd3 = open("./2.txt",O_RDWR);
if(fd3==-1)
{
perror("open");
return -1;
}
if(pid1==0)
{
char buf[100];
int len = read(fd1,buf,sizeof(buf));
write(fd3,buf,len/2);
printf("拷贝成功\n");
}
else if(pid1>0)
{
pid_t pid2;
pid2 = fork();
if(pid2==0)
{
char buf[100];
int len = read(fd2,buf,sizeof(buf));
lseek(fd2,len/2,SEEK_SET);
int len1 = read(fd2,buf,sizeof(buf));
lseek(fd3,len/2,SEEK_SET);
write(fd3,buf,len1);
printf("拷贝成功\n");
}
else if(pid2>0)
{
wait(NULL);
wait(NULL);
exit(EXIT_SUCCESS);
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
运行结果: