James
James

Reputation: 3709

Wait for a Unix Domain socket to be bound

I am writing a client app which connects to a server process through a Unix domain socket. If the server process is not running, I want the client to wait until the server has started and is listening for connections on the socket.

Currently I have a retry loop in the client which calls connect() every second until it successfully connects to the socket.

Is there any function I can call which will simply block until a particular named socket (e.g. "/var/mysock") is created and bound to a server process?

Upvotes: 8

Views: 2722

Answers (2)

Kean
Kean

Reputation: 602

I know this is a very old question but this may help newcomers who arrive here via Google with the same problem.

If portability is a concern, and as a guiding principle it always should be, then the way you are doing it is entirely correct. Sometimes the obvious solution is also the correct one. If you are concerned about the overhead of attempting a connect() so frequently, in your try loop instead do a stat() on the socket and if that works, verify it really is a socket using the S_ISSOCK() macro that comes from stat.h. Only once all that is true do you try the connect().

The only time you would need to worry about fancy asynchronous notifications is if the client application can or should be doing other work while it waits for the server to start. This is not typical but I can envision cases where you may want to do that. In this case I would simply have the connection attempt in a separate thread. There are nuances here that I can go into if you feel it would be appropriate but I think it's overkill for a simple "wait for the server to come alive" type loop.

Upvotes: 3

JB.
JB.

Reputation: 42104

Not a full answer, but...

If you're on Linux, the inotify interface will let you trap a the first few useful steps of the operation:

  • unlink'ing a leftover former socket will trigger an IN_DELETE_SELF on it.
  • bind'ing will trigger an IN_CREATE on the parent directory.

Unfortunately, the server isn't connect'able until it listen's. Though this is the next logical step, there's really no guarantee it will do so right away. It doesn't look as though inotify provides an interface to that.

Upvotes: 4

Related Questions