#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
//信号量
sem_t sem1,sem2;
char str[20];
int res;
void* callBack1(void *arg)
{
int fd=open("./01_pthread_exit.c",O_RDONLY);
if(fd<0)
{
perror("open");
return NULL;
}
while(1)
{
sem_wait(&sem1);
res=read(fd,str,sizeof(str));
if(res==0)
{
printf("文件读取完毕\n");
sem_post(&sem2);
break;
}
sem_post(&sem2);
}
close(fd);
pthread_exit(NULL);
}
void* callBack2(void *arg)
{
while(1)
{
sem_wait(&sem2);
write(1,str,res);
if(res==0)
{
printf("文件打印完毕\n");
sem_post(&sem1);
break;
}
sem_post(&sem1);
}
}
int main(int argc, const char *argv[])
{
//创建并初始化信号量
if(sem_init(&sem1,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
perror("sem_init");
return -1;
}
pthread_t tid_front,tid_end;
//创建两个分支线程
//读取文件内容进程
if(pthread_create(&tid_front,NULL,callBack1,NULL)!=0)
{
perror("pthread_create");
return -1;
}
//打印文件内容进程
if(pthread_create(&tid_end,NULL,callBack2,NULL)!=0)
{
perror("pthread_create");
return -1;
}
//主线程阻塞等待分支进程退出
pthread_join(tid_front,NULL);
pthread_join(tid_end,NULL);
//销毁信号量
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}