2

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.

1
  • Why the downvote? Anything I can change? Commented Jul 12, 2014 at 18:07

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. That works great!! I also needed to add a Thread.sleep(156) below the command execution to give it time to execute. I found, on my computer, that 156ms was the minimum amount of time I could use.
@user3731821 I've edited my answer to point out Process.waitFor. Definitively more robust than empirical timing ;)
For some reason, that doesn't wait long enough on my computer. I bind the socket directly after I kill the processes on the port, Should I be doing something else first?

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.