创建两个程序拷贝文件,其中一个线程拷贝前半部分,另一个线程拷贝后半部分
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
//创建互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct Msg
{
int fd_r;
int fd_w;
off_t size;
};
void *callBack1(void *arg)
{
int fd_r = ((struct Msg *)arg)->fd_r;
int fd_w = ((struct Msg *)arg)->fd_w;
off_t size = ((struct Msg *)arg)->size;
char c;
//上锁
pthread_mutex_lock(&mutex);
lseek(fd_r,0,SEEK_SET);
lseek(fd_w,0,SEEK_SET);
for(int i = 0;i<size/2;i++)
{
read(fd_r,&c,1);
write(fd_w,&c,1);
}
//解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *callBack2(void *arg)
{
int fd_r = ((struct Msg *)arg)->fd_r;
int fd_w = ((struct Msg *)arg)->fd_w;
off_t size = ((struct Msg *)arg)->size;
char c;
//上锁
pthread_mutex_lock(&mutex);
lseek(fd_r,size/2,SEEK_SET);
lseek(fd_w,size/2,SEEK_SET);
for(int i=size/2;i<size;i++)
{
read(fd_r,&c,1);
write(fd_w,&c,1);
}
//解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
int fd_r = open("./1.png",O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
int fd_w = open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
off_t size = lseek(fd_r,0,SEEK_END);
struct Msg Cres;
Cres.fd_r = fd_r;
Cres.fd_w = fd_w;
Cres.size = size;
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack1,&Cres) != 0)
{
fprintf(stderr,"pthread_create failed __%d__",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callBack2,&Cres) != 0)
{
fprintf(stderr,"pthread_create failed __%d__",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
close(fd_r);
close(fd_w);
return 0;
}