从 Java 运行 bash [英] Running bash from Java

查看:26
本文介绍了从 Java 运行 bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一些类似的事情.

I want to do something along these lines.

    Process shell = Runtime.getRuntime().exec("/bin/bash");

然后我想使用 shell 进程的流与 bash shell 对话.然而,这似乎根本不起作用,它完全难倒了我.

Then I want to use the streams for the shell process to talk to the bash shell. However this doesn't seem to work at all and it totally stumps me.

我发现了这个 链接 似乎在谈论同样的问题.为什么会发生这种情况,是否有比链接中列出的更好的解决方案?

I found this link which seems to talk about the same problem. Why exactly does this happen and are there better solutions than the one outlined in the link?

推荐答案

可能有必要将您的写入从 JVM 刷新到子进程以确保其获得输入.IIRC 我不需要在 Windows 上这样做,但在 Linux 上这样做了.我还遇到了一些问题,我不得不强制子进程刷新写入,以便 JVM 也能立即看到它们.

It can be necessary to flush your writes from the JVM to the child process to make sure its getting its input. IIRC I didn't need to do this on Windows, but did on Linux. I also ran into issues where I had to force the child process to flush writes so the JVM would see them right away too.

另外,在你做任何事情之前,确保你有 JVM 线程从 stdout 和 stderr 读取,如果这些缓冲区中的任何一个填满了它可以锁定进程.这是 Windows 上的一个大问题.如果您在启动进程时使用选项组合流,您将只需要一个线程.

Also, make sure that you have JVM threads reading from stdout and stderr before you do anything, if either of those buffers fills up it can lock the process. This is a huge problem on Windows. You will only need one thread if you use the options to combine the streams when launching the process.

此外,您的示例(上面)没有换行符,bash 不需要换行符吗?例如触摸等等\n"

Also, your example (above), doesn't have a newline, wouldn't bash require one? e.g. "touch blah\n"

这篇关于从 Java 运行 bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆