简体   繁体   中英

Flex using Pipes in C

I recently started learning about Flex and I have a question. I have a simple C code that prints a couple of strings and I want the output of this program to be the input to a flex program. For that I tried the following command:

./t | ./note

Code for tc:

#include <time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv){

    printf("alfred nota: 79 \n");
    fflush(stdout);
    sleep(5);
    printf("alfred nota: 79 \n");
    fflush(stdout);
    printf("alfred nota: 79 \n");
    fflush(stdout);

    return 0;
}

Code for note.l

%{
%}

%%
"nota: 79" { printf("Saiu nota 79\n"); }
.|\n  {;}
%% 

int yywrap(){
    return(1);
}

int main(){
    yylex();
    return(0);
}

What I wanted was so that the flex program would receive one line from the tc program and scan it with note.l and then receive the next string and scan it and so on. But what seems to happen is that the note.l won't start running unless the tc ends, which isn't what I want. So my question is, how do I remedy this?

Thanks in advance.

You can change flex behavior to use read rather than stdio:

This can be done in one of two ways:

option 1

use -Cr to generate your lexer:

flex -Cr -o note.c note.l

Or

option 2

put it into your lex file:

%{
%}

%option read
%%
"nota: 79" { printf("Saiu nota 79\n"); }
.|\n  {;}
%% 

int yywrap(){
    return(1);
}

int main(){
    yylex();
    return(0);
}

Using read will turn off io buffering for flex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM