2016-02-17 90 views
2

我正在尝试使用折返lex和yacc编写一个简单的计算器应用程序。在这里我想创建两个线程(解析器),它应该解析输入文件中提供的输入。线路输入文件解析两个线程之间划分..警告:赋值使整数指针没有投射yylval = atoi(yytext);

我的简单的计算器代码法是

%option reentrant bison-bridge 
%option noyywrap 
%{ 
#include<stdio.h> 
void yyerror(char *); 
#include "y.tab.h" 
%} 

%% 

[0-9]+ { 
     yylval=atoi(yytext); 
     return INTEGER; 
     } 

[-+\n] return *yytext; 

[ \t] ;/* Skip whitespaces*/ 

.  ; 

%% 

为简单的计算器(折返)我的yacc文件

%pure-parser 
%lex-param {void * scanner} 
%parse-param {void * scanner} 
%{ 
     #include <pthread.h> 
     #include <sys/types.h> 
     #include <sys/stat.h> 
     #include <fcntl.h> 
     #include<stdio.h> 
     #include <stdlib.h> 
     int f[2]; 
     pthread_mutex_t lock; 
     int cnt=0; 
     void* scanfunc(void *); 
%} 

%token INTEGER 

%% 

program: program expr '\n'  {printf("%d\n", $2);} 
     | 
     ; 

expr: INTEGER     {$$=$1;} 
     |expr '+' expr   {$$=$1+$3;} 
     |expr '-' expr   {$$=$1-$3;} 
     ; 

%% 

void yyerror(char *s){ 
     fprintf(stderr,"%s\n",s); 
} 
int main(int argc, char *argv[]){ 
     pthread_t threads[2]; 
     int n=2,i;//Number of threads to be created 
     //set_file_ptr(); 

     if(argc!=2){ 
       printf("Insufficient nos. of arguments\n"); 
       exit(0); 
     } 
     for(i=0;i<n;i++){ 
       f[i]=open(argv[1],O_RDONLY); 
       lseek(f[i],i*30,SEEK_SET); 
     } 
     printf("File pointer set\n"); 

     pthread_mutex_init(&lock,NULL); 
     for(i=0;i<n;i++){ 
       pthread_create(&threads[i], NULL, (void *)scanfunc, (void *)&i); 
     } 

     //join all threads 
     for(i=0;i<n;i++){ 
       pthread_join(threads[i],NULL); 
     } 

     pthread_mutex_destroy(&lock); 
     //yyparse(); 
     return 0; 
} 
void* scanfunc(void * i) 
{ 
    void * scanner; 
    // printf("Value of i is %d\n",*(int *)i); 
    printf("Starting thread %d...\n", *(int *)i); 
    yylex_init(&scanner); 
    printf("Done scanner init\n"); 
    pthread_mutex_lock(&lock); 
    printf("Thread with id %d obtained lock\n",cnt); 
    yyset_in(f[cnt],scanner); 
    cnt++; 
    pthread_mutex_unlock(&lock); 
    yyparse(scanner); 
    yylex_destroy(scanner); 
} 

和我的输入文件是

12+12 
14-12 
23-11 
12-12 
23-45 
67+45 
11+23 
45-12 
67-12 
90-34 
56-56 
90-45 

当我编译和当我调试用gdb它说,计划接收信号SIGSEGV,分割过错低于行这个程序运行这个程序,我得到followign输出

File pointer set 
Starting thread 0... 
Starting thread 0... 
Done scanner init 
Thread with id 0 obtained lock 
Done scanner init 
Thread with id 1 obtained lock 
Segmentation fault (core dumped) 

yyparse(scanner); 

我无法找到如何调试此程序。 帮助他的方面表示赞赏。 谢谢

回答

0

yyin必须是FILE*而不是int。通过int预计FILE*不会有令人满意的结果;段错误并非意外。

我很惊讶你没有得到一堆警告,当你试图编译该代码。

+0

我在文件作出必要的修改,按照你的建议。现在我得到所有的零值作为输出。我期待在输入文件中提供的算术表达式的结果作为输出。当我编译时,我得到以下警告'purelex.l:12:8:warning:赋值使得整型指针没有转换[缺省情况下启用] yylval = atoi(yytext);'我也想限制第一个线程来证明第一行第六行和第二行,处理接下来的六行,目前没有发生。 – user2201980

+0

我正在编译以上程序** $ lex purelex.l **,后跟** $ yacc pureyacc.y **和** $ gcc -o purecalc lex.yy.c y.tab.c -lpthread ** – user2201980

相关问题