一. 思维导图
二. 练习
1). 使用多线程拷贝文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
typedef struct {
int start;
int len;
char src[20];
char dest[20];
}file_info;
void copy_file(FILE *srcfp, FILE *destfp, int start, int len) {
int count = 0;
char buf[5];
fseek(srcfp, start, SEEK_SET);
fseek(destfp, start, SEEK_SET);
while(1) {
int read = fread(buf, 1, sizeof(buf), srcfp);
if (read == 0 || count > len) {
fwrite(buf, 1, read - (count - len), destfp);
break;
}
fwrite(buf, 1, read, destfp);
}
}
void *task1(void *arg) {
file_info *info = (file_info*)arg;
FILE *srcfp, *destfp;
if ((srcfp = fopen(info->src, "r")) == NULL) {
perror("src");
exit(EXIT_SUCCESS);
}
if ((destfp = fopen(info->dest, "w")) == NULL) {
perror("dest");
exit(EXIT_SUCCESS);
}
copy_file(srcfp, destfp, info->start, info->len);
}
void *task2(void *arg) {
file_info *info = (file_info*)arg;
FILE *srcfp, *destfp;
if ((srcfp = fopen(info->src, "r")) == NULL) {
perror("src");
exit(EXIT_SUCCESS);
}
if ((destfp = fopen(info->dest, "w")) == NULL) {
perror("dest");
exit(EXIT_SUCCESS);
}
copy_file(srcfp, destfp, info->start, info->len);
}
int main(int argc, const char *argv[]) {
if (argc != 3) {
printf("参数数量错误 \n");
return -1;
}
FILE *fp;
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("src open");
return -1;
}
int len = fseek(fp, 0, SEEK_SET);
fclose(fp);
pthread_t tid1, tid2;
file_info info1 = {0, len/2};
strcpy(info1.src, argv[1]);
strcpy(info1.dest, argv[2]);
file_info info2 = {len/2, len/2};
strcpy(info2.src, argv[1]);
strcpy(info2.dest, argv[2]);
if (pthread_create(&tid1, NULL, task1, &info1)) {
perror("task 1");
return -1;
}
if (pthread_create(&tid2, NULL, task2, &info2)) {
perror("task 2");
return -1;
}
printf("a \n");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
结果展示: