2024/4/16作业

1. 

 #include<stdio.h>
 #include<pthread.h>
 #include<sys/types.h>
 #include<sys/stat.h>
 #include<fcntl.h>
 #include<unistd.h>
 #include<string.h>
 
 typedef struct picture{
     int fd1;
     int fd2;
     size_t size;
     pthread_mutex_t *mutex;
 }File;
 
 
 void *callback1(void *arg)
 {
     int fd1 = ((File*)arg)->fd1;
     int fd2 = ((File*)arg)->fd2;
     size_t size = ((File*)arg)->size;
     pthread_mutex_t *mutex = ((File*)arg)->mutex;
     pthread_mutex_lock(mutex);
     lseek(fd1, 0, SEEK_SET);
     lseek(fd2, 0, SEEK_SET);
     char buf;
     for(int i=0;i<size/2;i++)
     {
         read(fd1,&buf,1);
         write(fd2,&buf,1);
     }
     printf("前半部分拷贝完毕\n");
     pthread_mutex_unlock(mutex);
     return NULL;
 }
 
 
 void *callback2(void *arg)
 {
     int fd1 = ((File*)arg)->fd1;
     int fd2 = ((File*)arg)->fd2;
     size_t size = ((File*)arg)->size;
     pthread_mutex_t *mutex = ((File*)arg)->mutex;
     pthread_mutex_lock(mutex);
     lseek(fd1, size/2, SEEK_SET);
     lseek(fd2, size/2, SEEK_SET);
     char buf;
     for(int i=size/2;i<size;i++){
         read(fd1,&buf,1);
         write(fd2,&buf,1);
     }
     printf("后半部分拷贝完毕\n");
     pthread_mutex_unlock(mutex);
     return NULL;
 }
 
 int main(int argc, const char *argv[])
 {
     int fd1=open("./1.jpeg",O_RDONLY);                                   
     if(fd1 < 0)
     {
         perror("open");
         return -1;
     }
     int fd2=open("./2.jpeg",O_WRONLY|O_CREAT|O_TRUNC,0777);
     if (fd2 < 0) {
         perror("open");
         return -1;
     }
     off_t size = lseek(fd1,0,SEEK_END);
     pthread_t tid1,tid2;
     pthread_mutex_t mutex;
     File file;
     file.fd1 = fd1;
     file.fd2 = fd2;
     file.size = size;
     file.mutex = &mutex;
     pthread_mutex_init(&mutex,NULL);
     if(pthread_create(&tid1,NULL,callback1,(void *)&file)!=0)
     {
         printf("pthread_create failed __%d__\n",__LINE__);
         return -1;
     }
 
     if(pthread_create(&tid2,NULL,callback2,(void *)&file)!=0)
     {
         printf("pthread_create failed __%d__\n",__LINE__);
         return -1;
     }
     pthread_join(tid1,NULL);
     pthread_join(tid2,NULL);
     pthread_mutex_destroy(&mutex);
     close(fd1);
     close(fd2);
     return 0;
 }
 

运行结果 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值