1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <sys/mman.h>
5 #include <fcntl.h>
6 #include <string.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9
10 int fCopy(char *fName[],int num)
11 {
12 int fd1 = 0;
13 int fd2 = 0;
14 char* p1 = NULL;
15 char* p2 = NULL;
16 int fSize = 0;
17 int offset = 0;
18 int move = 0;
19 int add = 0;
20 pid_t pid = 0;
21 struct stat st;
22
23 stat(fName[1],&st);
24
25 fSize=st.st_size;
26
27 fd1=open(fName[1],O_RDWR);
28 if(fd1==-1)
29 {
30 perror("open file1");
31 exit(-1);
32 }
33
34 fd2=open(fName[2],O_RDWR|O_CREAT,0777);
35 if(fd2==-1)
36 {
37 perror("open file2");
38 exit(-2);
39 }
40
41 ftruncate(fd2,fSize);
42
43 p1=mmap(NULL,fSize,PROT_READ,MAP_SHARED,fd1,0);
44 if(p1==MAP_FAILED)
45 {
46 perror("mmap file1");
47 exit(-3);
48 }
49
50 p2=mmap(NULL,fSize,PROT_WRITE,MAP_SHARED,fd2,0);
51 if(p2==MAP_FAILED)
52 {
53 perror("mmap file2");
54 exit(-4);
55 }
56
57 if(num==0)
58 {
59 memcpy(p2,p1,fSize);
60
61 munmap(p1,fSize);
62 munmap(p2,fSize);
63
64 close(fd1);
65 close(fd2);
66
67 printf("finished\n");
68 }
69 else
70 {
71 offset=fSize/num;
72 add=fSize%num;
73 }
74
75 for(int i=0;i<num;i++)
76 {
77 int move=offset*i;
78 pid=fork();
79 if(pid==-1)
80 {
81 perror("fork");
82 exit(1);
83 }
84 else if(pid==0)
85 {
86 memcpy(p2+move,p1+move,offset);
87 break;
88 }
89 }
90
91 if(pid>0)
92 {
93 for(int i=0;i<num;i++)
94 {
95 wait(NULL);
96 }
97
98 memcpy(p2+fSize-add,p1+fSize-add,add);
99 munmap(p1,fSize);
100 munmap(p2,fSize);
101
102 close(fd1);
103 close(fd2);
104
105 printf("finished\n");
106 }
107
108 return 0;
109 }
110 int main(int argc,char *argv[])
111 {
112 if(argc<3)
113 {
114 printf("error:Too few argumemts\n");
115 exit(0);
116 }
117 else if(argc>4)
118 {
119 printf("error:Too more arguments\n");
120 exit(0);
121 }
122
123 int num=0;
124
125 if(argc==3||strcmp(argv[3],"-f"))
126 {
127 printf("please input the number of processes:");
128 scanf("%d",&num);
129 }
130
131 printf("waiting.......\n");
132 fCopy(argv,num);
133
134 return 0;
135 }