#include <head.h>
#include <semaphore.h>
int fd1;
sem_t sem1, sem2;
char buf[100] = " ";
int ret;
void *callBack(void *arg)
{
while (1)
{
sem_wait(&sem1);
ret = read(fd1, buf, sizeof(buf));
if (ret == 0)
{
sem_post(&sem2);
break;
}
sem_post(&sem2);
}
}
int main(int argc, char const *argv[])
{
sem_init(&sem1, 0, 1);
sem_init(&sem2, 0, 0);
if ((fd1 = open("cat1.c", O_RDONLY)) == -1)
PRINT_ERR("1");
pthread_t tid;
if (pthread_create(&tid, NULL, callBack, NULL))
PRINT_ERR("pthread_create");
printf("创建线程成功\n");
while (1)
{
sem_wait(&sem2);
// printf("%s", buf);
// bzero(buf,sizeof(buf));
write(1,buf,ret);
if (ret == 0)
{
sem_post(&sem1);
break;
}
sem_post(&sem1);
}
pthread_join(tid, NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
close(fd1);
return 0;
}
模仿cat啊
于 2022-11-14 17:29:59 首次发布