1、使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源
代码:
#include<myhead.h>
#define BUFSIZE 128
// 线程函数参数结构体
typedef struct
{
char *srcfile; // 源文件路径
char *destfile; // 目标文件路径
off_t start; // 拷贝起始位置
int len; //文件大小
} copy_args_t;
//定义求源文件大小的函数
int get_file_len(const char *srcfile, const char *destfile)
{
//以只读的形式打开源文件
int sfd = open(srcfile, O_RDONLY);
if(sfd == -1)
{
perror("open srcfile error");
return -1;
}
//以创建的形式打开目标文件
int dfd = open(destfile, O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(dfd == -1)
{
perror("open destfile error");
return -1;
}
int size = lseek(sfd, 0, SEEK_END);
//关闭文件
close(sfd);
close(dfd);
return size; //将文件大小返回
}
// 线程函数,负责拷贝文件的一部分
void *copyfile(void *arg)
{
copy_args_t *args = (copy_args_t *)arg; //类型转换获取参数
char buf[BUFSIZE]; //搬运工
int sum = 0;
int sfd = open(args->srcfile, O_RDONLY);
if (sfd == -1)
{
perror("open source file");
pthread_exit(NULL);
}
int dfd = open(args->destfile, O_WRONLY);
if (dfd == -1)
{
perror("open destination file");
close(sfd);
pthread_exit(NULL);
}
//移动光标位置
lseek(sfd, args->start, SEEK_SET);
lseek(dfd, args->start, SEEK_SET);
while (1)
{
//从源文件中读取数据
int res = read(sfd, buf, BUFSIZE);
sum +=res; //将读取个数累加
if(res == 0 || sum>args->len) //表示文件读取结束
{
write(dfd, buf, res-(sum-args->len)); //父进程将最后一次拷贝结束
break;
}
//写入到目标文件中
write(dfd, buf, res);
}
close(sfd);
close(dfd);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
//判断文件个数是否正确
if (argc != 3)
{
fprintf(stderr, "Usage: %s <srcfile> <destfile>\n", argv[0]);
return 1;
}
const char *srcfile = argv[1];
const char *destfile = argv[2];
// 获取源文件大小
int lenth = get_file_len(srcfile, destfile);
pthread_t tid1, tid2;
copy_args_t args1 = { .srcfile = (char *)srcfile, .destfile = (char *)destfile, .start = 0, .len = lenth/2 };
copy_args_t args2 = { .srcfile = (char *)srcfile, .destfile = (char *)destfile, .start = lenth/2, .len = lenth - lenth/2 };
//创建线程
if (pthread_create(&tid1, NULL, copyfile, &args1))
{
perror("pthread_create");
return -1;
}
if (pthread_create(&tid2, NULL, copyfile, &args2))
{
perror("pthread_create");
pthread_join(tid1, NULL); // 等待线程1结束
return -1;
}
pthread_join(tid1, NULL); // 等待线程1结束
pthread_join(tid2, NULL); // 等待线程2结束
printf("拷贝成功!\n");
return 0;
}
运行结果:
思维导图: