1

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();
     }
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

at least in java 8: Runtime.getRuntime().exec(new String[]{"sh", "-c", "iscsiadm -m discovery -t st -p iscsiInfo.ipAddress &&" +" ls /var/lib/iscsi/nodes"})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.