版权声明: https://blog.csdn.net/dashoumeixi/article/details/84670375
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#define BUFFSIZE 8192
#define NBUFF 10
struct {
struct{
ssize_t readbytes; //读取的字节 。 如果是0 则读完
char data[BUFFSIZE]; //缓冲区
}buf[NBUFF]; //N个缓冲区
sem_t nempty , nstored; //生产者/消费者信号量
}share;
static void * producer(void*p)
{
int readfd = *(int*)p;
int nindex = 0; // buff index;
while(1){
sem_wait(&share.nempty);
share.buf[nindex].readbytes = read(readfd,share.buf[nindex].data,BUFFSIZE);
if(share.buf[nindex].readbytes <= 0){
sem_post(&share.nstored);
break;
}
if(++nindex >= NBUFF)
nindex = 0;
sem_post(&share.nstored);
}
return 0;
}
static void * consumer(void*p)
{
int writefd = *(int*)p;
int nindex = 0;
int bytes = 0;
while(1){
sem_wait(&share.nstored);
//检查是否读完了或者出错了
bytes = share.buf[nindex].readbytes;
if(bytes <= 0){
break;
}
bytes = write(writefd,share.buf[nindex].data,bytes);
printf("write bytes:%d\n" , bytes);
if(++nindex >= NBUFF)
nindex = 0;
sem_post(&share.nempty);
}
return 0;
}
int main(int argc ,char **argv)
{
if(argc < 3){
puts("srcfile destfile");
return 0;
}
int readfd = open(argv[1],O_RDONLY);
int writefd = open(argv[2],O_CREAT|O_WRONLY|O_TRUNC,0644);
if(readfd < 0 || writefd < 0){
perror("open failed");
exit(0);
}
sem_init(&share.nempty,0,NBUFF);
sem_init(&share.nstored,0,0);
pthread_t tid_producer , tid_consumer;
pthread_create(&tid_producer,NULL,producer,(void*)&readfd);
pthread_create(&tid_consumer,NULL,consumer,(void*)&writefd);
pthread_join(tid_producer,NULL);
pthread_join(tid_consumer,NULL);
return 0;
}