Java 程序标准输出并从前台分离
我有一个java程序,比方说Test.class。
当我执行 java Test 时,程序要求输入密码,然后继续。
问题在于标准输出被重定向到日志,并且程序是通过 & 启动的。 (我们在 UNIX 上)。
我如何与启动 java Test & 的程序进行交互?与标准输入和标准输出?
一种可能的解决方案是在前台启动程序,然后在满足条件后从 java 在后台运行它。
谢谢!
I have a java program, let's say Test.class.
When I execute java Test the program ask for a Password and then continute.
The problem is that the stdout is redirected to a log and the program is launched with the & ( we are on UNIX).
How can i interact with this program launched java Test & with the stdin and stdout?
One possible solution is to start the program in foreground and then after a condition run it in background from java.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果程序可以从 stdin 读取密码,您可以有一个 Unix 脚本提示输入密码,然后启动 Java 应用程序并将密码传递给它,例如:
或者您可以考虑将 Java 应用程序分成两部分;可能有一个交互式“前端”部分来验证密码,然后一旦验证了密码,就可以启动“后端”部分作为后台进程并退出。
If the program can read the password from stdin, you can have a Unix script prompt for the password, then start the Java application and pass the password to it, e.g.:
Or you can consider to split your Java application in two parts; there could be one interactive "front-end" part that validates the password, and then once the password is validated this could launch a "back-end" part as a background process and exit.
一种选择是使用 echo 将输入传输到程序:
或者,如果输入数量很大,您也可以将输入放入文件中并将文件内容重定向为:
One option is to pipe the input to your program using
echo
s as:Alternatively if the number of inputs are large you can also put your inputs in a file and redirect the file contents as:
我在这个问题中没有看到任何 Java 特定的内容,如果您想根据应用程序输出驱动标准输入,您可以使用 Expect 实用程序: http://en.wikipedia.org/wiki/Expect
但请注意,Expect 非常脆弱,您最好不要在生产场景中使用它。
I don't see anything Java specific in this question, if you want to drive the stdin based on the application output, you can use the Expect utility: http://en.wikipedia.org/wiki/Expect
Beware though, Expect is notoriously fragile, you'd do wise to refrain from using it in production scenarios.
实际上,如果您只想输入密码,也许您可以尝试在前台启动应用程序(不带尾随 &)。
然后,输入密码后,按 Ctrl+Z 或在另一个 shell 中执行
kill -SIGSTP
以挂起程序。最后,输入bg
将其置于后台。有关详细信息,请阅读有关 shell 作业控制功能的文档。
Actually if you only want to be able to enter the password, perhaps you can try launching your app in foreground (without the trailing &).
Then, after you have entered the password, press Ctrl+Z or in another shell do
kill -SIGSTP <pid>
in order to suspend your program. Finally, typebg
to put it in background.Read the docs about your shell's job-control functionality for details.