day27——homework
1、使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
void *copy_first_half(void *arg)
{int fd1 = ((int *)arg)[0];int fd2 = ((int *)arg)[1];off_t filesize = lseek(fd1, 0, SEEK_END);lseek(fd1, 0, SEEK_SET);off_t half_size = filesize / 2-1;char buffer[1];ssize_t bytes_read;off_t start = 0;while (1){bytes_read = read(fd1, buffer, sizeof(buffer));write(fd2, buffer, bytes_read);if (start >= half_size){break;}start += bytes_read;}return NULL;
}
void *copy_second_half(void *arg)
{sleep(1);int fd1 = ((int *)arg)[0];int fd2 = ((int *)arg)[1];off_t filesize = lseek(fd1, 0, SEEK_END);off_t half_size = filesize / 2;lseek(fd1, half_size, SEEK_SET);char buffer[1];ssize_t bytes_read;off_t start = half_size;while (1){bytes_read = read(fd1, buffer, sizeof(buffer));write(fd2, buffer, bytes_read);if (start >= filesize){break;}start += bytes_read;}return NULL;
}
int main()
{int fd1 = open("source.txt", O_RDONLY | O_CREAT, 0664);int fd2 = open("destination.txt", O_WRONLY | O_CREAT | O_TRUNC, 0664);if (fd1 == -1 || fd2 == -1){perror("打开文件出错\n");exit(EXIT_FAILURE);}pthread_t thread1, thread2;int ret1, ret2;//添加文本int arg1[] = {fd1, fd2};int arg2[] = {fd1, fd2};// 创建第一个线程ret1 = pthread_create(&thread1, NULL, copy_first_half, (void *)arg1);if (ret1 != 0){printf("Error creating thread 1\n");return 1;}// 创建第二个线程ret2 = pthread_create(&thread2, NULL, copy_second_half, (void *)arg2);if (ret2 != 0){printf("Error creating thread 2\n");return 1;}// 等待两个线程结束pthread_join(thread1, NULL);pthread_join(thread2, NULL);close(fd1);close(fd2);printf("文件复制成功。\n");return 0;
}