Running PHP from Java

后端 未结 2 1417
遥遥无期
遥遥无期 2021-01-16 16:35

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         


        
相关标签:
2条回答
  • 2021-01-16 16:40

    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.

    0 讨论(0)
  • 2021-01-16 16:51

    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.
    • the command is writing the version information to its "error" stream rather than its "output" stream.

    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:

    1. Start the process.
    2. Wait for the process to complete
    3. Read the output from the process.

    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.

    0 讨论(0)
提交回复
热议问题