创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
#include <myhead.h>
int main(int argc, const char *argv[])
{
/*
创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
*/
pid_t pid;
pid = fork();
int len;
if(pid == 0)
{
#if 1
int fd,fd1;
fd = open("./1.txt",O_RDONLY);
fd1 = open("./2.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd==-1)
{
perror("open");
return -1;
}
if(fd1==-1)
{
perror("open");
return -1;
}
len = lseek(fd,0,SEEK_END);
int t = len/2;
if(t%2 != 0)
{
t++;
}
lseek(fd,0,SEEK_SET);
char s[5];
read(fd,s,t);
write(fd1,s,t);
close(fd);
close(fd1);
#endif
exit(0);
}
else if(pid > 0)
{
pid_t pid2;
pid2 = fork();
if(pid2 == 0)
{
sleep(2);
int fd,fd1;
fd = open("./1.txt",O_RDONLY);
fd1 = open("./2.txt",O_WRONLY|O_CREAT|O_APPEND,0664);
if(fd==-1)
{
perror("open");
return -1;
}
if(fd1==-1)
{
perror("open");
return -1;
}
len = lseek(fd,0,SEEK_END);
int t = len/2;
if(t%2 != 0)
{
t++;
}
lseek(fd,t,SEEK_SET);
lseek(fd1,0,SEEK_END);
char s[5];
read(fd,s,t);
write(fd1,s,t);
close(fd);
close(fd1);
exit(0);
}
else if(pid2 > 0)
{
sleep(4);
int fd,fd1;
fd = open("./1.txt",O_RDONLY);
fd1 = open("./2.txt",O_RDONLY);
len = lseek(fd,0,SEEK_END);
if(fd1==-1)
{
perror("open");
return -1;
}
char buf[102400];
lseek(fd1,0,SEEK_SET);
read(fd1,buf,len);
printf("%s\n",buf);
close(fd);
close(fd1);
wait(NULL);
wait(NULL);
usleep(3);
exit(0);
}
}
else
{
perror("fork");
exit(1);
}
return 0;
}