IO作业day4
xmind
作业:创建子父进程,子进程将1.txt内容拷贝到2.txt中,父进程将3.txt内容拷贝到4.txt中。
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid == 0)
{
int fp1 = open("./2.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fp1 == -1)
{
perror("open fp1");
return -1;
}
int fp2 = open("./1.txt",O_RDONLY);
if(fp2 == -1)
{
perror("open fp2");
return -1;
}
char s[100];
while(1)
{
int p = read(fp2,s,sizeof(s));
if(p==0)
{
break;
}
write(fp1,s,p);
}
close(fp1);
close(fp2);
}
else if(pid > 0)
{
int fp3 = open("./4.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fp3 == -1)
{
perror("open fp3");
return -1;
}
int fp4 = open("./3.txt",O_RDONLY);
if(fp4 == -1)
{
perror("open fp4");
return -1;
}
char a[100];
while(1)
{
int p = read(fp4,a,sizeof(a));
if(p==0)
{
break;
}
write(fp3,a,p);
}
close(fp3);
close(fp4);
}
else
{
perror("fork");
return -1;
}
return 0;
}