Linux学习笔记(C语言):用无名管道实现英文词典的查询

要求输入单词,输出单词的详细解释(进程间通信)

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAX 19661//字典行数,一行一个词

int main(int argc, const char *argv[])
{
	int pipefd[2];
	int ret = pipe(pipefd);
	if(-1 == ret)
	{
		perror("pipe");
		exit(1);
	}
	pid_t pid = fork();
	if(pid>0)
	{
		close(pipefd[0]);
		int dict_fd = open("./dict.txt",O_RDONLY);//字典文本文件,一行一个词
		if(-1 == dict_fd)
		{
			perror("open dict");
			exit(1);
		}
		char buf[4096]={0};
		int rd_ret=0;

		while(1)
		{
			rd_ret = read(dict_fd,buf,sizeof(buf));
			if(0 == rd_ret)
			{
				lseek(dict_fd,0,SEEK_SET);
				continue;
			}
			write(pipefd[1],buf,rd_ret);

		}
		close(pipefd[1]);
		close(dict_fd);

	}
	else if(0 == pid)
	{
		close(pipefd[1]);
		char want_word[256]={0};
		char *arg[2]={NULL};
		int num = 0 ;
		FILE* fp = fdopen(pipefd[0],"r");
		if(NULL == fp )
		{
			perror("fdopen fd[0]");
			exit(1);
		}
		while(1)
		{
			num = 0 ;
			printf("please input word:\n"); 
			fgets(want_word,256,stdin);
			want_word[strlen(want_word)-1]='\0';
			if(0 == strcmp(want_word,"#exit"))
			{
				exit(1);	
			}
			while(1)
			{
				char line[1024]={0};
				fgets(line,1024,fp);
				arg[0]=strtok(line," ");
				arg[1]=strtok(NULL,"\n");
				if(0 == strcmp(arg[0],want_word))
				{
					printf("%s:%s\n",arg[0],arg[1]);
					break;
				}
				num++;
				if(num>MAX)
				{
					printf("not find %s\n",want_word);
					break;
				}
			}
		}
	}
	else
	{
		perror("fork");
		exit(1);
	}
	return 0;
}

词典文本
运行结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值