i know this is very ugly, but just for fun.
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- int main(int argc, char **argv)
- {
- char *src_file, *des_file;
- int src_fd = -1, des_fd = -1;
- int pid, i, ret, np, len, unit;
- int f_index, r_index;
- char *src_ptr = NULL, *des_ptr = NULL;
- np = 2;
- src_file = argv[1];
- des_file = argv[2];
- src_fd = open(argv[1], O_RDONLY);
- if (src_fd <0) {
- perror("open");
- goto __end;
- }
- des_fd = open(argv[2], O_RDWR | O_CREAT, 0644);
- if (des_fd <0) {
- perror("open");
- goto __end;
- }
- len = lseek(src_fd, 0, SEEK_END);
- lseek(src_fd, 0, SEEK_SET);
- src_ptr = (char *)mmap(NULL, len, PROT_READ, MAP_SHARED, src_fd, 0);
- if (src_ptr == MAP_FAILED) {
- perror("mmap src_ptr");
- goto __end;
- }
- if (ftruncate(des_fd, len) <0) {
- perror("ftruncate");
- goto __end;
- }
- des_ptr = (char *)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, des_fd, 0);
- if (des_ptr == MAP_FAILED) {
- perror("mmap des_ptr");
- goto __end;
- }
- unit = len/np == 0 ? len : len/np;
- for (i = 0; i <np; i++) {
- pid = fork();
- if (pid == 0)
- break;
- }
- if (pid == 0) {
- f_index = i*unit;
- r_index = (i+1)*unit> len ? len : (i+1)*unit;
- memcpy(des_ptr + f_index, src_ptr + f_index, r_index - f_index);
- }
- else {
- while (i) {
- if ((ret = waitpid(-1, NULL, 0))<0)
- perror("waipid\n");
- else {
- i--;
- printf("complete: %f\n", (np-i)/(float)np);
- }
- }
- }
- __end:
- if (src_fd>= 0)
- close(src_fd);
- if (des_fd>= 0)
- close(des_fd);
- if (src_ptr != MAP_FAILED)
- munmap(src_ptr, len);
- if (des_ptr != MAP_FAILED)
- munmap(des_ptr, len);
- return 0;
- }
来源: http://www.bubuko.com/infodetail-3123040.html