作业
创建子父进程,子进程将1.txt内容拷贝到2.txt中,父进程将3.txt内容拷贝到4.txt中。
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t ID;
ID = fork();
if(ID > 0)
{
int fd1;
fd1 = open("./3.txt",O_RDONLY);
if( fd1 == -1)
{
perror("open");
return -1;
}
int fd2;
fd2 = open("./4.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
if( fd2 == -1)
{
perror("open");
return -1;
}
char buf[5];
ssize_t len1;
while((len1 = read(fd1,buf,sizeof(buf))) != 0)
{
write(fd2,buf,len1);
}
printf("拷贝成功\n");
close(fd1);
close(fd2);
}
else if(ID == 0)
{
int fd3;
fd3 = open("./1.txt",O_RDONLY);
if( fd3 == -1)
{
perror("open");
return -1;
}
int fd4;
fd4 = open("./2.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
if( fd4 == -1)
{
perror("open");
return -1;
}
char buff[5];
ssize_t len2;
while((len2 = read(fd3,buff,sizeof(buff))) != 0)
{
write(fd4,buff,len2);
}
printf("拷贝成功\n");
close(fd3);
close(fd4);
}
else
{
perror("fork");
return -1;
}
while(1);
return 0;
}
运行结果:
知识梳理