作业:创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
#include <myhead.h>
int main(int argc, const char *argv[])
{
int fd=open("copy.txt",O_RDONLY);
if(fd==-1)
{
perror("open");
return -1;
}
int fd1=open("1.txt",O_WRONLY|O_TRUNC|O_CREAT,0664);
if(fd1==-1)
{
perror("open1");
return -1;
}
int fd2=open("2.txt",O_TRUNC|O_WRONLY|O_CREAT,0664);
if(fd2==-1)
{
perror("open2");
return -1;
}
long filesize=lseek(fd,0,SEEK_END);
printf("%ld",filesize);
char fun1[filesize/2];
char fun2[filesize-filesize/2];
read(fd,fun1,filesize/2);
read(fd,fun2,filesize-filesize/2);
pid_t pid;
pid=fork();
if(pid==0)
{
printf("大娃\n");
write(fd1,fun1,filesize/2);
sleep(5);
exit(EXIT_SUCCESS);
}
else if(pid>0)
{
pid_t pid2;
pid2=fork();
if(pid2==0)
{
printf("二娃\n");
write(fd2,fun2,filesize-filesize/2);
sleep(5);
exit(EXIT_SUCCESS);
}
else if(pid2>0)
{
printf("儿子,过来,我是你爸爸\n");
wait(NULL);
wait(NULL);
sleep(3);
exit(EXIT_SUCCESS);
}
}
else
{
perror("fork");
return -1;
}
close(fd);
close(fd1);
close(fd2);
return 0;
}
x-mind