gpt4 book ai didi

java - 命令行进程未从标准输入接收任何内容

转载 作者:行者123 更新时间:2023-12-02 08:16:02 26 4
gpt4 key购买 nike

我有一个等待击键退出的命令行应用程序。该进程从 Java 启动正常,但当我发送击键 (a) 时,没有任何反应。看起来应用程序从未从标准输入接收任何内容。这是一个代码示例:

Process p = Runtime.getRuntime().exec("\"C:\\app.exe\"");
Thread.sleep(5000);
OutputStream out = p.getOutputStream();
out.write(97);
out.flush();
out.close();
p.waitFor();

如果我只是从命令行执行它,它就可以正常工作。有谁知道问题出在哪里吗?

谢谢!

最佳答案

您需要读取 getInputStream 和 getErrorStream 这两个流,否则您的程序可能会永远阻塞,请参阅 JavaDoc

The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

关于java - 命令行进程未从标准输入接收任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6428125/

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