要求创建两个线程,实现文件打印到终端上,类似cat一个文件

要求创建两个线程,实现文件打印到终端上,类似cat一个文件:

        1.A线程读取文件中的内容

        2.B线程将A线程中读取到的数据打印到终端上

        3.当文件打印完毕后,结束进程。

程序:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <semaphore.h>
sem_t sem;
sem_t sem1;
char c=0;
int fd_r;

void *func(void *arg)
{
	while(1)
	{
		ssize_t res;
	/***********临界区********/
		
		sem_wait(&sem);
		res=read(fd_r,&c,1);
		sem_post(&sem1);
		if(res==0)
		{
			pthread_exit(NULL);
		
		}
	}
	
}
void *func1(void *arg)
{
	while(1)
	{
	/***********临界区********/
	sem_wait(&sem1);
	printf("%c",c);
	sem_post(&sem);
	
	}

}
int main(int argc, const char *argv[])
{
	//打开文件
	fd_r=open("./pipe.c",O_RDONLY);
	//创建2个信号量
	sem_init(&sem,0,1);
	sem_init(&sem1,0,0);
	//创建2个线程
	pthread_t tid;
	pthread_t tid1;

	if(pthread_create(&tid,NULL,func,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed");
		return -1;
	
	}
	if(pthread_create(&tid1,NULL,func1,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed");
		return -1;
	
	}
	pthread_detach(tid1);
	pthread_join(tid,NULL);
	//销毁信号量
	sem_destroy(&sem);
	sem_destroy(&sem1);
	close(fd_r);
	return 0;
}

运行效果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值