Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Perl-Script from Java (embedded in Perl)

Tags:

java

pipe

perl

eof

Perl accepts a scipt via STDIN. After pressing CTRL-D perl knows the "End of Script". After doing so, the script is executed.

Now my question: I wand to do that from Java.

  1. Open Process Perl
  2. Copy Script into STDIN of Perl-Process
  3. HOW DO I SIGNAL PERL THE CRTL-D WITHOUT CLOSING THE STREAM (from within java)
  4. Send some input to the Script
  5. get some Output from Script.

proc = Runtime.getRuntime().exec("perl", env);
commandChannel = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
responseChannel = new BufferedReader(new InputStreamReader(proc.getInputStream()));
InputStreamReader mymacro = new InputStreamReader(getClass().getResourceAsStream("macro.perl"));

char[] b = new char[1024];
int read;

try
{
    while ((read = mymacro.read(b)) != -1)
    {
        commandChannel.write(b, 0, read);
    }
    commandChannel.flush();
    PERL IS WAITING FOR END OF SCRIPT; ??
}  ...
like image 774
user1025189 Avatar asked Nov 05 '22 11:11

user1025189


2 Answers

But this exactly what CTRL-D does: closing the STDIN of the process. So in your case closing the proc.getInputStream() is the appropriate action to have the expected behavior as you simulate it in the shell.

If you want to do "something else" just do it. Like writing a special command to your script via STDIN which then interprets it as such and jumps into another state or whatever is desired

like image 134
Patrick B. Avatar answered Nov 09 '22 16:11

Patrick B.


this example does exactly what you need:

public class TestPl {
public static void main(String[] args) {
  Process proc;
  try {
     proc = Runtime.getRuntime().exec("perl");
     // a simple script that echos stdin.
     String script = "my $s=<>;\n" +
                     "print $s;";

     OutputStreamWriter wr = new OutputStreamWriter(proc.getOutputStream());

     //write the script:
     wr.write(script);

     //signal end of script:
     wr.write(4);
     wr.write("\n");

     //write the input:
     wr.write("bla bla bla!!!");

     wr.flush();
     wr.close();

     String output = readFromInputStream(proc.getInputStream());
     proc.waitFor(); 
     System.out.println("perl output:\n"+output);
  } catch (IOException e) {
     e.printStackTrace();
  } catch (InterruptedException e) {
     e.printStackTrace();
  }
}

public static String readFromInputStream(InputStream inputStream) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
  String line;
  StringBuffer buff = new StringBuffer();
  while ((line=br.readLine())!=null){
     if (buff.length() > 0){
        buff.append("\n");
     }
     buff.append(line);
  }
  br.close();
  return buff.toString();
}

}

like image 35
Yotam Madem Avatar answered Nov 09 '22 17:11

Yotam Madem