创建子父进程,子进程将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 fd3,fd4;
fd3 = open("./3.txt",O_RDONLY);
if(fd3==-1)
{
perror("open");
return -1;
}
fd4 = open("./4.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd4==-1)
{
perror("open");
return -1;
}
char buff[100];
int len = read(fd3,buff,sizeof(buff));
write(fd4,buff,len);
close(fd3);
close(fd4);
//printf("父进程中:%d\n",ID);
}
else if(ID==0)
{
int fd1,fd2;
fd1 = open("./1.txt",O_RDONLY);
if(fd1==-1)
{
perror("open");
return -1;
}
fd2 = open("./2.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd2==-1)
{
perror("open");
return -1;
}
char buf[100];
int len1 = read(fd1,buf,sizeof(buf));
write(fd2,buf,len1);
close(fd1);
close(fd2);
//printf("子进程的ID是:%d\n",ID);
}
else
{
perror("fork");
return -1;
}
//while(1);
return 0;
}