题目:
使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源
#include <myhead.h>
// 定义一个用于传递数据的结构体类型
struct File
{
int fd1; // 源文件描述符
int fd2; // 目标文件描述符
int start; // 拷贝的起始位置
int end; // 拷贝的结束位置
};
void *task1(void *arg)
{
// 获取结构体变量
struct File *file = (struct File *)arg;
// 置位光标
off_t bytes_read = file->start;
// 定义缓冲区用于数据读写
char buf[128];
lseek(file->fd1, file->start, SEEK_SET);
lseek(file->fd2, file->start, SEEK_SET);
// 读取源文件
while (bytes_read < file->end)
{
int count = read(file->fd1, buf, sizeof(buf));
if (count <= 0)
return 0;
// 写目标文件
write(file->fd2, buf, count);
bytes_read += count;
}
}
void *task2(void *arg)
{
// 获取结构体变量
struct File *file = (struct File *)arg;
// 置位光标
off_t bytes_read = file->start;
// 定义缓冲区用于数据读写
char buf[128];
lseek(file->fd1, file->start, SEEK_SET);
lseek(file->fd2, file->start, SEEK_SET);
// 读取源文件
while (bytes_read < file->end)
{
int count = read(file->fd1, buf, sizeof(buf));
if (count <= 0)
return 0;
// 写目标文件
write(file->fd2, buf, count);
bytes_read += count;
}
}
int main(int argc, const char *argv[])
{
if (argc != 3)
{
printf("文件传入失败\n");
return EXIT_FAILURE;
}
// 打开两个文件
int source_fd = -1, copy_fd = -1;
source_fd = open(argv[1], O_RDONLY);
copy_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);
// 检查文件打开是否成功
if (source_fd == -1 || copy_fd == -1)
{
printf("文件打开失败\n");
return EXIT_FAILURE;
}
// 定义结构体变量
struct File file;
file.fd1 = source_fd;
file.fd2 = copy_fd;
// 获取源文件大小
int file_size = lseek(source_fd, 0, SEEK_END);
int half_size = file_size / 2;
// 定义线程变量
pthread_t tid1, tid2;
// 定义结构体变量
file.start = 0;
file.end = half_size;
// 创建两个线程
if (pthread_create(&tid1, NULL, task1, &file) != 0)
{
printf("tid1 创建失败\n");
return -1;
}
printf("tid1 创建成功\n");
// 改结构体变量
file.start = half_size;
file.end = file_size;
if (pthread_create(&tid2, NULL, task2, &file) != 0)
{
printf("tid2 创建失败\n");
return -1;
}
printf("tid2 创建成功\n");
// 阻塞等待线程的结束
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("拷贝成功\n");
return 0;
}