Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
James Avatar asked Sep 03 '09 08:09

James


People also ask

How do you bind a socket in UNIX?

After a UNIX domain socket is created, you must bind the socket to a unique file path by using the bind function. Unlike internet sockets in the AF_INET domain where the socket is bound to a unique IP address and port number, a UNIX domain socket is bound to a file path.

Are UNIX domain sockets reliable?

Valid socket types in the UNIX domain are: SOCK_STREAM, for a stream-oriented socket; SOCK_DGRAM, for a datagram-oriented socket that preserves message boundaries (as on most UNIX implementations, UNIX domain datagram sockets are always reliable and don't reorder datagrams); and (since Linux 2.6.

How do UNIX domain sockets work?

Unix sockets are bidirectional. This means that every side can perform both read and write operations. While, FIFOs are unidirectional: it has a writer peer and a reader peer. Unix sockets create less overhead and communication is faster, than by localhost IP sockets.

Do UNIX domain sockets use ports?

Unix Domain Socket uses a local file on the device. It does not require network ports to be open, instead the Linux system controls who can have access to the file for communication. This is advantageous as you can assign permissions that suit the way you want to set up the system.


1 Answers

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.

like image 117
JB. Avatar answered Oct 19 '22 03:10

JB.