tags:

views:

67

answers:

2

I'd like to run something like (in myProgram.sh):

java -cp whatever.jar com.my.program $1

within PHP and read the output.

So far I have something like:

$processOrderCommand = 'bash -c "exec nohup setsid /myProgram.sh ' . $arg1 . ' > /dev/null 2>&1 &"';
exec($processOrderCommand);

But what I'd really like is to be able to get the output of the java program within the PHP script and not just execute it as another thread.

How can this be done?

+4  A: 

You can do this :

exec($processOrderCommand, $output);

From the documentation :

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

For a better control on your execution you can take a look at proc_open()


Resources :

Colin Hebert
Unfortunately this doesn't work with Java output. Even just running java -version returns an empty array.
Stephane Grenier
@Stephane Grenier that's because the output of `-version` is on the error stream ;)
Colin Hebert
@Colin: I just ran exec('java -cp hardcodedPath/TestOutput.jar com.my.TestProgram hello', $output); The result was an empty array. In the program, I just do a System.out.println(args[0]) // ie. hello. Any suggestions?
Stephane Grenier
@Stephane Grenier, Well in that case I must admit that I don't really understand why this doesn't work. Anyway, I suggest you to look `proc_open()` which will help you to handle streams easier.
Colin Hebert
Could there be anything to do with php permissions in that it's returning nothing? And if so, how would you check?
Stephane Grenier
Also when I run shell_exec('which java') it returns empty...
Stephane Grenier
A: 

The key is that the classpaths need to be absolute within the shell_exec PHP script.

Or at least that's the only way I could get it to correctly work. Basically it's almost impossible to tell from environment to environment what the relative directory is that the php script is running the JVM.

As well, it helped to put the absolute path location for java, such as usr/.../bin/java

Stephane Grenier