#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
sem_t sem1,sem2;
void *fun1 (void *a)
{
sem_wait(&sem1);
int f1,f2;
f1 = open("./1.txt",O_RDONLY);
char arr;
int i=0;
while(read(f1,&arr,1)>0)
{
i++;
}
close(f1);
f1 = open("./1.txt",O_RDONLY);
f2 = open("./011.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
int j=0;
while(read(f1,&arr,1)>0)
{
j++;
if(j<i/2)
write(f2,&arr,1);
}
close(f1);
close(f2);
printf("上半部分拷贝完成\n");
sem_post(&sem2);
pthread_exit(NULL);
}
void *fun2 (void *a)
{
sem_wait(&sem2);
int f1,f2;
f1 = open("./1.txt",O_RDONLY);
char arr;
int i=0;
while(read(f1,&arr,1)>0)
{
i++;
}
close(f1);
f1 = open("./1.txt",O_RDONLY);
f2 = open("./012.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
int j=0;
while(read(f1,&arr,1)>0)
{
j++;
if(j>i/2 || j==i/2)
write(f2,&arr,1);
}
close(f1);
close(f2);
printf("下半部分拷贝完成\n");
sem_post(&sem1);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
sem_destroy(&sem1);
sem_destroy(&sem2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}