进程输入流不返回进程输入(OSX)

时间:2017-06-15 01:51:56

标签: java macos process terminal

我正在尝试获取我使用流程构建器启动的流程的输出,但输出看起来像是AppleScript的内容,而不是流程的实际输出:

代码:

public static void main(String[] args) {
    System.out.println(getJavaOutput());
}

public static String getJavaOutput() {
    try {
        //kill -9 $(ps -p $PPID -o ppid=)
        String output = "";
        ProcessBuilder macBuilder = new ProcessBuilder("osascript", "-e",
                "tell application \"Terminal\" to do script \"jps -lV && exit\"");
        Process p2 = macBuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        String line;
        while((line = reader.readLine()) != null){
            output += line + System.getProperty("line.separator");
        }
        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }   
    return null;
}

预期产出:

2680 sun.tools.jps.Jps
1289 

实际输出:

tab 1 of window id 742

1 个答案:

答案 0 :(得分:0)

将您的方法更改为:

public static String getJavaOutput() {
    try {
        String output = "";
        ProcessBuilder macBuilder = new ProcessBuilder("/bin/bash", "-c", "jps -lV && exit");
        Process p2 = macBuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            output += line + System.getProperty("line.separator");
        }
        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}