title: How to know whether any process is bound to a Unix domain socket?
body: <p>I'm writing a Unix domain socket server for Linux.</p>
  
  <p>A peculiarity of Unix domain sockets I quickly found out is that, while creating a listening Unix socket creates the matching filesystem entry, closing the socket doesn't remove it. Moreover, until the filesystem entry is removed manually, it's not possible to <code>bind()</code> a socket to the same path again : <code>bind()</code> fails with <code>EADDRINUSE</code> if the path it is given already exists in the filesystem.</p>
  
  <p>As a consequence, the socket's filesystem entry needs to be <code>unlink()</code>'ed on server shutdown to avoid getting <code>EADDRINUSE</code> on server restart. However, this cannot always be done (i.e.: server crash). Most FAQs, forum posts, Q&amp;A websites I found only advise, as a workaround, to <code>unlink()</code> the socket prior to calling <code>bind()</code>. In this case however, it becomes desirable to know whether a process is bound to this socket before <code>unlink()</code>'ing it.</p>
  
  <p>Indeed, <code>unlink()</code>'ing a Unix socket while a process is still bound to it and then re-creating the listening socket doesn't raise any error. As a result, however, the old server process is still running but unreachable : the old listening socket is "masked" by the new one. This behavior has to be avoided.</p>
  
  <p>Ideally, using Unix domain sockets, the socket API should have exposed the same "mutual exclusion" behavior that is exposed when binding TCP or UDP sockets : "<em>I want to bind socket S to address A; if a process is already bound to this address, just complain !</em>" Unfortunately this is not the case...</p>
  
  <p>Is there a way to enforce this "mutual exclusion" behavior ? Or, given a filesystem path, is there a way to know, <em>via</em> the socket API, whether any process on the system has a Unix domain socket bound to this path ? Should I use a synchronization primitive external to the socket API (<code>flock()</code>, ...) ? Or am I missing something ?</p>
  
  <p>Thanks for your suggestions.</p>
  
  <p>Note : Linux's abstract namespace Unix sockets seem to solve this issue, as there is no filesystem entry to <code>unlink()</code>. However, the server I'm writing aims to be generic : it must be robust against both types of Unix domain sockets, as I am not responsible for choosing listening addresses.</p>