nn3112337 nn3112337 - 4 months ago 6
PHP Question

Pass a running jar commands with php

So I have a Java console jar that works with commands that I enter while its running.

Is this also possible with PHP? I know executing the jar is, with exec(), but I can't really pass the running jar commands or get its output.


What you'll want to do is initialize the jar with proc_open() instead of exec(). proc_open() allows you to have individual streams to read/write from/to the stdin/stdout/stderr of your Java process. So, you'll start the Java process, and then you'll use fwrite() to send commands to the stdin ($pipes[0]) of the Java process. See the examples on proc_open()'s documentation page for more info.

EDIT Here's a quick code sample (just a lightly modified version of the example on the proc_open docs):

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to

$process = proc_open('java -jar example.jar', $descriptorspec, $pipes);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], 'this is a command!');

    echo stream_get_contents($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";