It really is a matter of coordination between the two processes.
Here I wrote a quick 10 minute script (just for fun) that starts the JVM and sends an integer value that java parses and returns incremented .. which PHP will just send back ad-infinitum ..
Php.php
<?php echo 'Compiling..', PHP_EOL; system('javac Java.java'); echo 'Starting JVM..', PHP_EOL; $pipes = null; $process = proc_open('java Java', [0 => ['pipe', 'r'], 1 => ['pipe', 'w']], $pipes); if (!is_resource($process)) { exit('ERR: Cannot create java process'); } list($javaIn, $javaOut) = $pipes; $i = 1; while (true) { fwrite($javaIn, $i); // <-- send the number fwrite($javaIn, PHP_EOL); fflush($javaIn); $reply = fgetss($javaOut); // <-- blocking read $i = intval($reply); echo $i, PHP_EOL; sleep(1); // <-- wait 1 second }
Java.java
import java.util.Scanner; class Java { public static void main(String[] args) { Scanner s = new Scanner(System.in); while (s.hasNextInt()) {
To run the script, just put these files in one folder and do
$ php PHP.php
you should see how numbers are printed:
1 2 3 . . .
Note that although these numbers are printed by PHP, they are actually generated by Java
source share