要求输入单词,输出单词的详细解释(进程间通信)
#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;
}