我对 Java 中的交互过程有疑问。我有线程来读取 STDOUT 和 STDERR 以及一个线程来处理进程的输入。但是在进程终止之前,STDOUT 流中没有可用的数据。然后是一次打印整个输出。
DBG | Pipe action-STDERR started
DBG | Pipe action-STDIN started
DBG | Pipe action-STDOUT started
STDIN | Try to put some input.
STDIN | I cannot see any output.
STDIN | Nevertheless the interaction works.
STDIN | It works on background.
STDIN | Let's terminate the process to see the truth.
STDIN | quit
STDOUT | Enter some text, please: The text is 'Try to put some input.'
STDOUT | Enter some text, please: The text is 'I cannot see any output.'
STDOUT | Enter some text, please: The text is 'Nevertheless the'
STDOUT | Enter some text, please: The text is 'interaction works.'
STDOUT | Enter some text, please: The text is 'It works on background.'
STDOUT | Enter some text, please: The text is 'Let's terminate the process to see the truth.'
STDOUT | Enter some text, please: The text is 'quit'
STDOUT | Bye!
DBG | Trying to kill thread action-STDOUT
DBG | Trying to kill thread action-STDERR
DBG | Trying to kill thread action-STDIN
DBG | Pipe action-STDERR finished
DBG | Finished
DBG | Pipe action-STDIN finished
DBG | Pipe action-STDOUT finished
以 STDOUT 为前缀的行是进程写入的行。以 STDIN 为前缀的行是我写的行。以 DBG 为前缀的行是被测试的 Java 程序编写的作为调试信息的行。让我们尝试在系统控制台中执行相同的过程。
Enter some text, please: Text
The text is 'Text'
Enter some text, please: quit
The text is 'quit'
Bye!
这种行为完全符合我的期望。我被要求提供一些意见。我这样做并得到答案。
我很惊讶,我在网上找到了几篇帖子,包括 Stackoverflow,但没有任何答案被标记为可接受的解决方案。(例如,从 Java Process 读取 InputStream 时出现问题。)Java 开发人员似乎从未处理过交互式进程的执行。奇怪的是,非交互式进程的输出(如 ping)在进程运行时按顺序出现。没有任何问题。但是当进程正在等待用户输入时,输出会以某种方式被阻塞。