I am trying to run the following from java file.
I am trying to display the php version and later will change to run php files.
Process p = Runtime.get
You have to wait for the process to execute and you must separate the arguments :
Process p = Runtime.getRuntime().exec("cmd", "/C", "PHP/php.exe", "-v");
BufferedReader in = new BufferedReader(new InputStreamReader( p.getInputStream()));
p.waitFor();
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
BTW, any time you have a problem in running a process, it's a good idea to look also at the error stream.
I suspect that the problem is one of the following:
php.exe
is not running at all, for example, because PHP/php.exe
should be PHP\php.exe
or something.Either way, you need to try reading from the error stream. You should either see the version information or an error message from cmd
or php.exe
.
I should also explain in detail why @dystroy's answer is wrong.
What exec
does is to create a new external process to run the command. This process is connected up to the JVM so that when your application writes to the getOutput()
stream, that goes to the external processes "standard input", and when the external process writes to its "standard output" and "standard error", the data can be read using the getInput()
and getError()
streams respectively.
The connections between the respective streams are implemented using "pipes" that are provided by the operating system.
The thing about a pipe is that it only has a limited buffering capacity. If one process is writing to one end and the other process is not reading, the writing process will eventually be forced to stop writing. Or more precisely, it will block in a write system call, waiting for the pipeline to drain.
@dystroy's answer said to do this on the Java side:
But if the external process writes lots of output, it won't be able to complete, because it will get blocked while writing to the pipe. Meanwhile the Java side is waiting for the external process to complete BEFORE it starts to read the data from the pipe.
Deadlock.