#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
struct pthread
{
int fd_r;
int fd_w;
off_t size;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * callB(void * arg)
{ int fd_r = ((struct pthread*)arg)->fd_r;
int fd_w = ((struct pthread*)arg)->fd_w;
off_t size =( (struct pthread*)arg)->size;
off_t offset = 0;
char c= 0;
for(int i = 0;i<size/2;i++)
{ pthread_mutex_lock(&mutex);
lseek(fd_r,offset,SEEK_SET);
lseek(fd_w,offset,SEEK_SET);
if( read(fd_r,&c,1)<0)
{
perror("read");
return NULL;
}
if(write(fd_w,&c,1)<0)
{
perror("write");
return NULL;
}
offset = lseek(fd_r,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
printf("前面拷贝完成\n");
pthread_exit(NULL);
}
void * callA(void * arg)
{ int fd_r = ((struct pthread*)arg)->fd_r;
int fd_w = ((struct pthread*)arg)->fd_w;
off_t size =( (struct pthread*)arg)->size;
off_t offset = size/2;
char c= 0;
for(int i = size/2;i<size;i++)
{ pthread_mutex_lock(&mutex);
lseek(fd_r,offset,SEEK_SET);
lseek(fd_w,offset,SEEK_SET);
if( read(fd_r,&c,1)<0)
{
perror("read");
return NULL;
}
if(write(fd_w,&c,1)<0)
{
perror("write");
return NULL;
}
offset = lseek(fd_r,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
printf("后半拷贝完成\n");
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//定义两个文件描述符
int fd_r,fd_w;
//读取文件
if ((fd_r = open("./1.text",O_RDONLY)) < 0 )
{
perror("open");
return -1;
}
if ((fd_w = open("./2.text",O_WRONLY|O_CREAT|O_TRUNC,0664)) < 0 )
{
perror("open");
return -1;
}
off_t size = lseek(fd_r,0,SEEK_END );
struct pthread p;
p.size = size;
p.fd_r = fd_r;
p.fd_w = fd_w;
pthread_t thread1,thread2;
if( pthread_create(&thread1,NULL,callB,&p)!= 0)
{
perror("callB");
return -1;
}
if (pthread_create(&thread2,NULL,callA,&p)!=0)
{
perror("callA");
return -1;
}
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
close(fd_r);
close(fd_w);
pthread_mutex_destroy(&mutex);
return 0;
}