=head1 NAME - p2open This is an example of the use o "p2open" function =head1 SYNOPSIS a <- p2open(comand) pputs(a) str <- pgets(a) sexp <- pread(a) =head1 Description p2open creates a bidirectional pipe to an external command pputs writes a string to the command pgets reads a string from the command pread reads an sexp from tha command =head1 Using binary calculator... ?- a <- p2open("bc"); a ?- pputs(a,"2+3"); {} ?- pgets(a); 5 ?- pputs(a,"scale=50"); {} ?- pputs(a,"1/3"); {} ?- pgets(a); .33333333333333333333333333333333333333333333333333 =head1 Using a pipe to an user defined In the following example p2open is used to open a pipe to and from a command tha translate words between portuguese and english =head2 The CAMILA code #!/home/jj/bin/camilax -n a <- p2open("./dict.pl"); wordtr(word)=do(pputs(a,symstr(word)), pread(a)); trad(phrase) = < wordtr(x) | x <- phrase > ; ; Transating a single word: pp(wordtr('ela)); ; Transating a word sequence: x <- trad(<'ela,'é,'uma,'simpatica,'rapariga>); pp(x); pp( if(x == <'she, 'is, 'a, 'nice, 'girl> ) then ":-)))" else ":-(" ); p2close(a); =head2 External command "dict.pl" that makes the tranlation (PERL) #!/usr/local/bin/perl select(STDOUT); $| =1; # make STDOUT and STDIN unbuffered select(STDIN); $| =1; %dict = qw{ ela she é is uma a simpatica nice rapariga girl gato cat eu I sou am }; while (<>){ chop ; if(defined($dict{$_})){ print STDOUT "$dict{$_}\n";} else { print STDOUT "?\n";} } =head1 Warning Additionally, this is very dangerous as you may block forever. It assumes it's going to talk to something like bc, both writing to it and reading from it. This is presumably safe because you "know" that commands like bc will read a line at a time and output a line at a time. Programs like sort that read their entire input stream first, however, are quite apt to cause deadlock. The big problem with this approach is that if you don't have control over source code being run in the child process, you can't control what it does with pipe buffering. Thus you can't just open a pipe to cat -v and continually read and write a line from it. If you write a command to work as a pipe, be carefull to do it unbufferred: =head2 if you use C see: setbuf, setlinebuf =head2 if you use PERL select(STDOUT); $| =1; # make STDOUT and STDIN unbuffered select(STDIN); $| =1; =cut #!/home/jj/bin/camilax -n a <- p2open("./dict.pl"); wordtr(word)=do(pputs(a,symstr(word)), pread(a)); trad(phrase) = < wordtr(x) | x <- phrase > ; ; Transating a single word: pp(wordtr('ela)); ; Transating a word sequence: x <- trad(<'ela,'é,'uma,'simpatica,'rapariga>); pp(x); pputs(a,"souuuu"); princ("souuuu=",pread(a),"\n"); pp( if(x == <'she, 'is, 'a, 'nice, 'girl> ) then ":-)))" else ":-(" ); p2close(a); quit.