day22作业
创建3个子进程,子进程1拷贝文件的前一半,子进程2拷贝文件的后一半,父进程回收两个子进程资源
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid,pid2;
pid=fork();
if(pid==0)
{
printf("我是子进程1,我拷贝文件前一半\n");
int fd=open("./1.txt",O_RDONLY);
int fd2=open("./2.txt",O_CREAT|O_WRONLY|O_APPEND,0664);
int len=lseek(fd,0,SEEK_END);//文件长度
int mlen=len/2;
lseek(fd,0,SEEK_SET);
char ch[5];
int sum=0;
int yu=mlen%sizeof(ch);
printf("yu=%d\n",yu);
while(1)
{
//ssize_t rdlen=read(fd,ch,len/2);
ssize_t rdlen=read(fd,ch,sizeof(ch));
ssize_t wlen=write(fd2,ch,rdlen);
sum+=rdlen;
if(sum+2==mlen)
{
printf("退出了\n");
break;
}
}
close(fd);
close(fd2);
}
else if(pid>0)
{
printf("我是父进程啊\n");
pid2=fork();
if(pid2>0)
{
printf("我还是父进程啊\n");
while(waitpid(0,NULL,0)!=-1)
{
waitpid(0,NULL,0);
}
}
else if(pid2==0)
{
printf("我是子进程2,我拷贝文件后一半\n");
sleep(10);
int fd=open("./1.txt",O_RDONLY);
int fd2=open("./2.txt",O_CREAT|O_WRONLY|O_APPEND,0664);
int len=lseek(fd,0,SEEK_END);//文件长度
int mlen=len-len/2;
int a=lseek(fd,len/2,SEEK_SET);
lseek(fd2,len/2,SEEK_SET);
char ch[5];
int sum=0;
int yu=mlen%sizeof(ch);
while(1)
{
ssize_t rlen=read(fd,ch,sizeof(ch));
ssize_t wlen=write(fd2,ch,rlen);
sum+=rlen;
if(sum+yu==mlen)
{
printf("读完了\n");
break;
}
}
close(fd);
close(fd2);
}
}
return 0;
}
原文地址:https://blog.csdn.net/sinat_28344841/article/details/143695410
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!