
作业: 用父子进程拷贝文件:
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;
}
该程序是用C语言编写的,用于在Ubuntu系统中通过父子进程协同工作来拷贝文件。程序首先检查命令行参数,然后打开源文件和目标文件。父进程读取源文件的一半内容并写入目标文件,子进程处理剩余的一半。文件操作包括使用open(),read(),write(),lseek()等系统调用,并确保正确处理错误情况。
421

被折叠的 条评论
为什么被折叠?



