in reply to Re^3: Pipe autoflush
in thread Pipe autoflush

I want to make API for SAP, Polish-English/English-Polish translator. It works in such way:
zielony:~$ sap -a # green # typed by me Slownik angielsko-polski green - rzeczownik zielen, trawnik przymiotnik zielony greens - liczba mnoga warzywa grow green - zazielenic sie -p # zielony # also by me Slownik polsko-angielski zielony - przymiotnik green

Replies are listed 'Best First'.
Re^5: Pipe autoflush
by almut (Canon) on Aug 23, 2007 at 20:04 UTC

    Okay, I spoke of assistance... so, here's my go at it.

    The general problem you're facing is that you need some way to tell when the sap program1 finished sending output. As it currently is, it just stops sending stuff, and enters a fgets() call to wait for the next command/input. This is no good, because in your Perl code you cannot tell when to exit the loop reading the response from sap... In other words, you'd need to have some indication that the output ended, for example a blank line (kind of a "prompt" saying new input expected...). A blank line seems okay here, as the program itself doesn't appear to write empty lines — otherwise, you'd have to come up with some other prompt, but note that it has to be terminated by a newline, or else your <SAPR> would return it too late...

    A further complication is that sap is not flushing its stdout (which is block-buffered when being run without an interactive terminal). However, as it's open-source, you could easily patch the C source... Look for the input loop within main() (in sap.c, that is), and modify it to read

    ... for (;;) { // --- add this printf("\n"); // the prompt fflush(stdout); // make sure output gets written // --- if (fi) { if (!fgets(slowo,32,fi)) break; ...

    (and recompile the program by calling make ...)

    Then, your Perl code could look something like this:

    ... sub read_sap_response { while (my $line = <SAPR>) { last if $line =~ /^$/; # found "prompt" --> exit loop print $line; # show response } } my $pid = fork; if ($pid) { close PARENTR; close PARENTW; read_sap_response(); # this is needed, because we've patched the program to output # the blank line _before_ waiting for input (which was the # easiest option in this case...) while (1) { open FIFOR, "<fifo"; my $line = <FIFOR>; close FIFOR; print SAPW $line; read_sap_response(); } } else { close SAPR; close SAPW; open STDIN , '<&PARENTR'; open STDOUT, '>&PARENTW'; exec "sap"; die $!; }

    That should be it.  At least it works for me :)

    ___

    1 I'm specifically referring to this version, which I could find on the web.

      Thank you very very much for your help. I'm really grateful.

      I've understood all. Also was thinking about source editing, but would have liked Perl solution. However, it's good.