创建3个线程,一个子线程拷贝文件的前一半,另一个子线程拷贝文件的另一半,主线程回收子线程

#include <myhead.h>
int get_len(const char *p1,const char *p2)
{
    int fd1=open(p1,O_RDONLY);
    if(fd1==-1)
    {
        perror("open1");
        return -1;
    }
    int fd2=open(p2,O_WRONLY|O_CREAT|O_TRUNC,0664);
    if(fd2==-1)
    {
        perror("open2");
        return -1;
    }
    int len = lseek(fd1,0,SEEK_END);
    close(fd1);
    close(fd2);
    return len;
}
void *fun1(void *ggg)
{
    int len =get_len("./1.txt","./2,txt");
    int fd1,fd2;
    fd1=open("./1.txt",O_RDONLY);
    if(fd1==-1)
    {
        perror("open1");
        exit(EXIT_SUCCESS);
    }
    fd2=open("./2,txt",O_WRONLY);
    if(fd2==-1)
    {
        perror("open2");
        exit(EXIT_SUCCESS);
    }
    lseek(fd1,0,SEEK_SET);
    lseek(fd2,0,SEEK_SET);
    char buff[1024];
    int sum =0;
    while(1)
    {
        int res=read(fd1,buff,sizeof(buff));
        sum+=res;
        if(sum>=len/2||res==0)
        {
            write(fd2,buff,res-(sum-len/2));
                    break;
                    }
        return 0;
    }
}
void *fun2(void *ggg)
{
    int len=get_len("./1.txt","2.txt");
    int fd1,fd2;
    fd1=open("./1.txt",O_RDONLY);
    if(fd1==-1)
    {
        perror("open1");
        exit(EXIT_SUCCESS);
    }
    fd2=open("./2,txt",O_WRONLY);
    if(fd2==-1)
    {
        perror("open2");
        exit(EXIT_SUCCESS);
    }
    lseek(fd1,len/2,SEEK_SET);
    lseek(fd1,len/2,SEEK_SET);
    char buff[1024];
    int sum=0;
    while(1)
    {
        int res=read(fd1,buff,sizeof(buff));
        sum+=res;
        if(sum>=len/2||res==0)
        {
            write(fd2,buff,res-(sum-(len-len/2)));
            break;
        }
        write(fd2,buff,res);
    }
    return 0;
}


int main(int argc, const char *argv[])
{
    pthread_t tid1,tid2;
    if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
    {
        perror("ptcreat1");
        return -1;
    }
    if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
    {
        perror("ptcreat2");
        return -1;
    }
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值