xǝlɐ
xǝlɐ

Reputation: 63

Java- Execute Shell Command Not Working

I'm making a simple Java socket program that sends text from one computer to another.

Code:

    Scanner scan =  new Scanner(System.in);
    System.out.println("Starting Server...");
    ServerSocket server = new ServerSocket(7777);

The program binds the socket to port 7777 on line 3 on the code example above. However, this program sometimes returns a BindException. To fix that, I added this line of code before the bind occurs:


Runtime.getRuntime().exec("lsof -t -i:7777 | xargs kill");

So, in all:


    Scanner scan =  new Scanner(System.in);
    System.out.println("Starting Server...");
    Runtime.getRuntime().exec("lsof -t -i:7777 | xargs kill");
    ServerSocket server = new ServerSocket(7777);

This should run the shell command to kill any processes running on port 7777. But, it doesn't. If type the same command into Terminal.app, It works, and if I use the same syntax as line 4 of the above example and use a different command, like "say hello", that command works, but not the kill one.


So,

Why does that command not execute?

Thanks.

Upvotes: 2

Views: 2737

Answers (1)

Sylvain Leroux
Sylvain Leroux

Reputation: 52060

Runtime.exec will not launch the command through a shell, whereas this is required as you use a pipe. Try that instead:

Runtime.getRuntime().exec(
              new String[]{"sh","-c","lsof -t -i:7777 | xargs kill"},
              null, null);

I you need to wait for completion before continuing execution, use Process.waitFor:

Process p = Runtime.getRuntime().exec(
              new String[]{"sh","-c","lsof -t -i:7777 | xargs kill"},
              null, null);
int exitCode = p.waitFor()

Upvotes: 8

Related Questions