Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need a command that will wait for a process to start accepting requests on a specific port.

Is there something in linux that does that?

while (checkAlive -host localhost -port 13000 == false)
  do some waiting

...
share|improve this question

2 Answers 2

up vote 8 down vote accepted

The best test to see if a server is accepting connections is to actually try connecting. Use a regular client for whatever protocol your server speaks and try a no-op command.

If you want a lightweight TCP or UDP client you can drive simply from the shell, use netcat. How to program a conversation depends on the protocol; many protocols have the server close the connection on a certain input, and netcat will then exit.

while ! echo exit | nc localhost 13000; do sleep 10; done

You can also tell netcat to exit after establishing the connection.

while nc -q 1 localhost 13000 </dev/null; do sleep 10; done

An alternative approach is to wait for the server process to open a listening socket.

while netstat -lnt | awk '$4 ~ /:13000$/ {exit 1}'; do sleep 10; done

Or you might want to target a specific process ID:

while ! lsof -n -Fn -p $pid | grep -q '^n.*:13000$'; do sleep 10; done

I can't think of any way to react to the process starting to listen to the socket (which would avoid a polling approach) short of using ptrace.

share|improve this answer
    
I think netcat is the answer, so thank you. To clarify, what I'm trying to do is write a script as part of a load balancing procedure. I need to start a process, wait for it to accept requests on the port and then shutdown the original. If there are better ways of doing this, rather than writing my own script, I'm all ears. –  Will Dec 31 '10 at 16:36
    
@Will: That's a very different question! I've written a different answer. –  Gilles Dec 31 '10 at 17:37
1  
I like netcat solution too. I have a script using nc -w 2 </dev/null >/dev/null — if the connection takes more than 2 seconds, it times out and fails — which is handy for my usage. –  ephemient Jan 9 '11 at 23:10

If you have bash and coreutils (e.g. timeout, sleep), but not nc/lsof/netstat, you can use this solution which uses bash magic tcp sockets:

while ! timeout 1 bash -c "echo > /dev/tcp/localhost/13000"; do sleep 10; done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.