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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值