繁体   English   中英

通过php传递正在运行的jar命令

[英]Pass a running jar commands with php

因此,我有一个Java控制台jar,它可以处理我在运行时输入的命令。
PHP也可以吗? 我知道用exec()执行jar,但是我真的不能传递正在运行的jar命令或获取其输出。

您要做的是使用proc_open()而不是exec()初始化jar。 proc_open()允许您使用单独的流来从Java进程的stdin / stdout / stderr中读取/写入。 因此,您将启动Java进程,然后使用fwrite()将命令发送到Java进程的stdin( $pipes[0] )。 有关更多信息,请参见proc_open()的文档页面上的示例。

编辑这是一个快速的代码示例(只是proc_open docs上示例的一个轻微修改的版本):

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$process = proc_open('java -jar example.jar', $descriptorspec, $pipes);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], 'this is a command!');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM