0

Using this code and getting error: try { Process p = Runtime.getRuntime().exec(“(lsof -i:10723 | grep node | awk ‘{print $2;}’)“);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        // read the output from the command
        String s = null;
        System.out.println(“Here is the standard output of the command:\n”);
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command

        System.out.println(“Here is the standard error of the command (if any):\n”);
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception e) {
    e.printStackTrace();
    }

1 Answers1

2

The problem is that you cannot do this:

exec("(lsof -i:10723 | grep node | awk '{print $2;}')");

The exec method does not understand shell syntax. It will split that command string into a command name and arguments where it sees whitespace.

So the name of the command that exec tries to execute is (lsof ... which does not exist. Hence the error message.

If you want to run a pipeline using exec, the simple way is to use a shell; e.g.

exec(new String[] {"sh", "-c",
                   "(lsof -i:10723 | grep node | awk '{print $2;}')"})
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks that worked for me :) – akhilesh gulati Jan 24 '18 at 05:10
  • String command[]={"/bin/sh", "-c","adb devices"}; But when I am trying to execute adb commands it is giving me "/bin/sh: adb: command not found – akhilesh gulati Jan 24 '18 at 05:10
  • That means that `adb` is either not installed, or not your shell's default `$PATH`. For the former: install it! For the latter, either change the default path, or use the absolute pathname for the `adb` command. Please note that this question is a Java question, not an Android question. There may be something Android specific in what yiou are trying to do that means that the above advice does not apply. – Stephen C Jan 24 '18 at 07:31