gpt4 book ai didi

java - 使用 php 传递正在运行的 jar 命令

转载 作者:行者123 更新时间:2023-12-02 03:32:39 24 4
gpt4 key购买 nike

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

最佳答案

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

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

$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";
}

关于java - 使用 php 传递正在运行的 jar 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com