Paweł Hajdan
Paweł Hajdan

Reputation: 18552

How to wait for an other process to start listening on a local port?

I have a test driver program that launches a separate test server process. The test server process listens on a local port, and after it's ready, the test driver runs a test that accesses the test server.

Currently the test driver repeatedly tries to connect to the local port (loop some, sleep some, try again). It's not an optimal solution, and is clearly unreliable.

Is it possible to wait for some event that says "somebody listens on a local port"? Trying to connect to early results in a "port closed" error.

I'd like to implement the solution on Windows, Linux, and Mac OS X. If you have some tips for any of these systems, it's welcome (it's probably going to be system-specific in each case).

Upvotes: 0

Views: 252

Answers (2)

Len Holgate
Len Holgate

Reputation: 21644

On Windows I use a named event for this kind of thing.

The test harness can create the event and communicate the name of the event to the server that it launches; it then waits on the event to be signalled before continuing the test. The server then connects to the event, initialises itself and once it's ready to accept connections it signals the event.

Upvotes: 1

Byron Whitlock
Byron Whitlock

Reputation: 53901

Well, if you launch the server process, you can intercept the stdout of the server right?

So have the server output "server started" when the socket ready. The driver should wait until the server sends this string to stdout, then try to connect to the server port.

Upvotes: 1

Related Questions