作业: 用父子进程拷贝文件:
ubuntu@ubuntu:~$ cat test6.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
if(argc!=3)//argv[1]:源文件;argv[2]:目标文件
{
perror("You Wrong");
return -1;
}
int myread=open(argv[1],O_RDONLY);
if(myread<0)
return -1;
int mywrite=open(argv[2],O_WRONLY|O_CREAT,0664);
if(mywrite<0)
return -1;
int len=lseek(myread,0,SEEK_END);
int count=0;
char buf[128];
pid_t pid=fork();
if(pid<0)
exit(-1);
else if(pid==0)
{
/*int myread=open(argv[1],O_RDONLY);
if(myread<0)
return -1;
int mywrite=open(argv[2],O_WRONLY|O_CREAT,0664);
if(mywrite<0)
return -1;*/
lseek(myread,0,SEEK_SET);
lseek(mywrite,0,SEEK_SET);
while(count<=len/2)
{
int cread=read(myread,buf,sizeof(buf));
count=count+cread;
if(count>len/2)
write(mywrite,buf,cread-(count-len/2));
else
write(mywrite,buf,cread);
bzero(buf,sizeof(buf));
}
}
else
{
wait(NULL);
lseek(myread,len/2+1,SEEK_SET);
lseek(mywrite,len/2+1,SEEK_SET);
count=len/2;
while(count<=len)
{
int myr=read(myread,buf,sizeof(buf));
count=count+myr;
write(mywrite,buf,sizeof(buf));
bzero(buf,sizeof(buf));
}
}
close(myread);
close(mywrite);
return 0;
}