模仿Linux cat指令打印文件内容到终端上
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
sem_t sem1,sem2;
char buf[128];
ssize_t res_r = 1,res_w = 1;
void* myread(void* arg)
{
while(1)
{
if(res_w < 0)
{
pthread_exit(NULL);
}
if(sem_wait(&sem1) < 0)
{
printf("__%d__",__LINE__);
perror("wait");
pthread_exit(NULL);
}
bzero(buf,sizeof(buf));
res_r = read(*(int*)arg,buf,sizeof(buf));
if(sem_post(&sem2) < 0)
{
printf("__%d__",__LINE__);
perror("post");
pthread_exit(NULL);
}
if(res_r < 0)
{
perror("read");
pthread_exit(NULL);
}
else if(0 == res_r)
{
printf("文件读取完毕\n");
pthread_exit(NULL);
}
}
}
void* print(void* arg)
{
while(1)
{
if(res_r < 0)
{
pthread_exit(NULL);
}
else if(0 == res_r)
{
printf("文件打印完毕\n");
pthread_exit(NULL);
}
if(sem_wait(&sem2) < 0)
{
printf("__%d__",__LINE__);
perror("wait");
pthread_exit(NULL);
}
res_w = write(1,buf,sizeof(buf));
if(sem_post(&sem1) < 0)
{
printf("__%d__",__LINE__);
perror("post");
pthread_exit(NULL);
}
if(res_w < 0)
{
perror("write");
pthread_exit(NULL);
}
}
}
int main(int argc, const char *argv[])
{
if(argc <2)
{
printf("请输入文件名\n");
return -1;
}
if(sem_init(&sem1, 0, 1) < 0)
{
printf("__%d__",__LINE__);
perror("init");
return -1;
}
if(sem_init(&sem2, 0, 0) < 0)
{
printf("__%d__",__LINE__);
perror("init");
return -1;
}
int fd_r = open(argv[1],O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,myread,(void*)&fd_r) != 0)
{
printf("__%d__",__LINE__);
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,print,NULL) != 0)
{
printf("__%d__",__LINE__);
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
if(sem_destroy(&sem1) < 0)
{
perror("destory");
return -1;
}
if(sem_destroy(&sem2) < 0)
{
perror("destory");
return -1;
}
close(fd_r);
return 0;
}