4

In ruby I have:

PTY.spawn("/usr/bin/lxc-monitor -n .+") do |i, o, pid|
  # ...
end

How do this in scala/java?

Timothy Klim
  • 1,257
  • 15
  • 25

2 Answers2

3

Try JPty or pty4j. These are implementations of pty for Java using JNA.

Dmitry Trofimov
  • 7,371
  • 1
  • 30
  • 34
2

I don't think that PTY has been ported to java/scala. You can use the built in Runtime from java.

  def run() {
    val rt = Runtime.getRuntime
    val cmds = Array("/usr/bin/lxc-monitor", "-n .+")
    val env = Array("TERM=VT100")
    val p1 = rt.exec(cmds, env)
  }

I used this page as the base for the scala version.

UPDATE:

To get the output you need to get the input stream and read it (I know this sounds backwards but it's input relative to the jvm). The example below uses apache commons to skip some verbose parts of java.

import java.io.StringWriter
import org.apache.commons.io.IOUtils

class runner {

  def run() {
    val rt = Runtime.getRuntime
    val cmds = Array("/usr/bin/lxc-monitor", "-n .+")
    val env = Array("TERM=VT100")
    val p1 = rt.exec(cmds, env)
    val inputStream = p1.getInputStream

    val writer = new StringWriter()
    IOUtils.copy(inputStream, writer, "UTF-8")
    val output = writer.toString()
    println(output)
  }

}

I got the apache utils idea from here.

Community
  • 1
  • 1
Noah
  • 13,821
  • 4
  • 36
  • 45
  • 1
    Indeed there is no PTY support in the Java standard library -- if you really need one (as opposed to just running a process and connecting to its stdin and stdout via streams, which a Java Process object will get you) you'll need to go through native code. The screenterm project at https://github.com/now/screenterm has support for this in its terminator.terminal.pty package. – RM. Jun 09 '12 at 21:55
  • Good point about connecting to stdin and stdout. The java version is a bit of a pain/verbose compared to PTY. – Noah Jun 09 '12 at 22:00
  • When I'm trying to get command output I get empty result. In ruby or python it works perfect. – Timothy Klim Jun 10 '12 at 09:03
  • 1
    `lxc-monitor` need a tty, but java don't have that. You can either do some hack with `expect` or just use `lxc-info` and friends. – J-16 SDiZ Jun 10 '12 at 14:35