typeof programmer
typeof programmer

Reputation: 1609

How to run multiple Linux commands using java.lang.process?

I have an example like the below showed. The command

iscsiadm -m discovery -t st -p iscsiInfo.ipAddress

will be executed here, what if I want to execute extra command after executing this, like

ls /var/lib/iscsi/nodes

how to do it using java.lang.process?

Add, I only need to execute the 1st command, but I need to get the 2nd command results and show it in GUI.

public static void main(String args[]) {
    try {
       String line;
       Process p = Runtime.getRuntime().exec("iscsiadm -m discovery -t st -p iscsiInfo.ipAddress");
       BufferedReader bri = new BufferedReader
        (new InputStreamReader(p.getInputStream()));
       BufferedReader bre = new BufferedReader
        (new InputStreamReader(p.getErrorStream()));
       while ((line = bri.readLine()) != null) {
         System.out.println(line);
       }
       bri.close();
       while ((line = bre.readLine()) != null) {
         System.out.println(line);
       }
       bre.close();
       p.waitFor();
       System.out.println("Done.");
     }
     catch (Exception err) {
       err.printStackTrace();
     }
}

Upvotes: 1

Views: 3553

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533640

You can run a shell which runs multiple commands.

e.g.

Runtime.getRuntime().exec("sh", "-c", 
          "iscsiadm -m discovery -t st -p iscsiInfo.ipAddress &&"
          +" ls /var/lib/iscsi/nodes");

If you use ProcessBuilder you can redirect the error to the standard output and have one stream to read.

Upvotes: 3

Related Questions