程序要求:
通过fork创建进程,子进程实现文件前半部分的拷贝,父进程实现文件后半部分的拷贝。
程序如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- int child_copy(int fd_dest,int fd_src,int len)
- {
- char buf[100];
- int n = 0,count = 0;
- memset(buf,0,sizeof(buf));
- lseek(fd_src,0,SEEK_SET);
- lseek(fd_dest,0,SEEK_SET);
- while((n = read(fd_src,buf,sizeof(buf))) > 0){
- write(fd_dest,buf,n);
- count += n;
- if(count > len / 2)
- break;
- }
- return 0;
- }
- int father_copy(int fd_dest,int fd_src)
- {
- char buf[100];
- int n = 0,count = 0;
- memset(buf,0,sizeof(buf));
- while((n = read(fd_src,buf,sizeof(buf))) > 0){
- write(fd_dest,buf,n);
- }
- return 0;
- }
- int main(int argc,char *argv[])
- {
- int fd_src,fd_dest;
- pid_t pid;
- int len;
-
- if(argc < 3){
- fprintf(stderr,"usage:%s srcfile destfile \n",argv[0]);
- exit(-1);
- }
- if((fd_src = open(argv[1],O_RDONLY)) < 0){
- perror("fail to open");
- exit(-1);
- }
- if((fd_dest = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0666)) < 0)
- {
- perror("fail to open");
- exit(-1);
- }
- len = lseek(fd_src,0,SEEK_END);
- if(ftruncate(fd_dest,len) < 0){
- perror("fail to change size");
- exit(-1);
- }
- if((pid = fork()) < 0){
- perror("fail to open");
- exit(-1);
- }else if(pid == 0){
- child_copy(fd_dest,fd_src,len);
- close(fd_dest);
- close(fd_src);
- exit(0);
- }else{
- close(fd_dest);
- close(fd_src);
-
- if((fd_src = open(argv[1],O_RDONLY)) < 0){
- perror("fail to open");
- exit(-1);
- }
- printf("fd_src : %d\n",fd_src);
- if((fd_dest = open(argv[2],O_WRONLY)) < 0)
- {
- perror("fail to open");
- exit(-1);
- }
- lseek(fd_src,len / 2,SEEK_SET);
- lseek(fd_dest,len / 2,SEEK_SET);
-
- father_copy(fd_dest,fd_src);
-
- close(fd_dest);
- close(fd_src);
- exit(0);
- }
-
- return 0;
- }
阅读(1374) | 评论(0) | 转发(0) |