9

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?

1
  • It looks like the issue is that the classpaths had to be absolute, relative, even if accurate, failed. I'll be posting the answer as soon as I can. Commented Sep 25, 2010 at 16:04

2 Answers 2

8

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 :

Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately this doesn't work with Java output. Even just running java -version returns an empty array.
@Stephane Grenier that's because the output of -version is on the error stream ;)
@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, 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.
Could there be anything to do with php permissions in that it's returning nothing? And if so, how would you check?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.