title: Unix Domain Socket: Using datagram communication between one server process and several client processes
body: <p>I would like to establish an IPC connection between several processes on Linux. I have never used UNIX sockets before, and thus I don't know if this is the correct approach to this problem.</p>
  
  <p>One process receives data (unformated, binary) and shall distribute this data via a local AF_UNIX socket using the datagram protocol (i.e. similar to UDP with AF_INET). The data sent from this process to a local Unix socket shall be received by multiple clients listening on the same socket. The number of receivers may vary.</p>
  
  <p>To achieve this the following code is used to create a socket and send data to it (the server process):</p>
  
  <pre><code>struct sockaddr_un ipcFile;
  memset(&amp;ipcFile, 0, sizeof(ipcFile));
  ipcFile.sun_family = AF_UNIX;
  strcpy(ipcFile.sun_path, filename.c_str());
  
  int socket = socket(AF_UNIX, SOCK_DGRAM, 0);
  bind(socket, (struct sockaddr *) &amp;ipcFile, sizeof(ipcFile));
  ...
  // buf contains the data, buflen contains the number of bytes
  int bytes = write(socket, buf, buflen);
  ...
  close(socket);
  unlink(ipcFile.sun_path);
  </code></pre>
  
  <p>This write returns -1 with errno reporting ENOTCONN ("Transport endpoint is not connected"). I guess this is because no receiving process is currently listening to this local socket, correct?</p>
  
  <p>Then, I tried to create a client who connects to this socket.</p>
  
  <pre><code>struct sockaddr_un ipcFile;
  memset(&amp;ipcFile, 0, sizeof(ipcFile));
  ipcFile.sun_family = AF_UNIX;
  strcpy(ipcFile.sun_path, filename.c_str());
  
  int socket = socket(AF_UNIX, SOCK_DGRAM, 0);
  bind(socket, (struct sockaddr *) &amp;ipcFile, sizeof(ipcFile));
  ...
  char buf[1024];
  int bytes = read(socket, buf, sizeof(buf));
  ...
  close(socket);
  </code></pre>
  
  <p>Here, the bind fails ("Address already in use"). So, do I need to set some socket options, or is this generally the wrong approach?</p>
  
  <p>Thanks in advance for any comments / solutions!</p>