How do i run a UNIX terminal from Java and send commands to it?

倖福魔咒の 提交于 2019-12-19 04:19:09

问题


Regarding the topic, the code below


    Process proc = null;
    try {
        String[] cmdss= {"gnome-terminal"};


        proc = Runtime.getRuntime().exec(cmdss, null, wd);
    } catch (IOException e) {
        e.printStackTrace();
    }

Runs the terminal form Ubuntu.

How do I issue commands into the terminal after running the termnal?

eg: running the terminal and run command such as "ls" etc.


回答1:


You can give gnome-terminal some options on the command line what it shall execute.

gnome-terminal -e /my/fortran/program

The -x option gives you roughly the same benefit but you can split the commandline into separate words.

Both -e and -x run the program with optional arguments while connecting the program`s standard input and output to the terminal. So the user can interact with the terminal properly.

Example:

gnome-terminal -x bash -c "ls; echo '<enter>'; read"

This will open the terminal and run the "program" bash. bash will get two arguments: -c and ls; echo ....; read. The -c option makes bash parsing and executing the next argument. This will call ls, then echo ... then read which waits for the return key.

In Java you must split the arguments appropriately into an array like this:

String cmd[] = {"gnome-terminal", "-x", "bash", "-c", "ls; echo '<enter>'; read" };


来源:https://stackoverflow.com/questions/7586858/how-do-i-run-a-unix-terminal-from-java-and-send-commands-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!