user1025189
user1025189

Reputation: 71

Running Perl-Script from Java (embedded in Perl)

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; ??
}  ...

Upvotes: 5

Views: 1245

Answers (2)

Yotam Madem
Yotam Madem

Reputation: 375

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();
}

}

Upvotes: 1

Patrick B.
Patrick B.

Reputation: 12343

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

Upvotes: 1

Related Questions