title: Sending file descriptor over UNIX domain socket, and select()
body: <p>I'm using a UNIX domain socket to transfer a file descriptor to another process. This works fine, but when I first try to see if socket is writeable using select(), the sendmsg() call fails with a Bad File Descriptor error. </p>
  
  <p>The sendmsg() function does work fine in combination with select() if I don't add the file descriptor info to the msghdr struct, so the conflict seems to be between select() and transferring file descriptors.</p>
  
  <p>I couldn't find any info on this in the man pages for select(), recvmsg(), or any other. Since this needs to become a server which hands out file descriptors to multiple processes, I'd still like to be able to use select().</p>
  
  <p>Is there anything I can do to make this work, or does anyone know of alternative solutions?</p>
  
  <p>Platform is Ubuntu 10.4.</p>
  
  <p>This is the code that initializes the structures:</p>
  
  <pre><code>
  
  struct cmsghdr_fd : public cmsghdr
  {
    int fd;
  };
  
  int sendfd(int sock, int fd)
  {
    struct msghdr hdr;
    struct iovec data;
    struct cmsghdr_fd msgdata;
  
    char dummy = '*';
    data.iov_base = &dummy;
    data.iov_len = sizeof(dummy);
  
    hdr.msg_name = NULL;
    hdr.msg_namelen = 0;
    hdr.msg_iov = &data;
    hdr.msg_iovlen = 1;
    hdr.msg_flags = 0;
  
    hdr.msg_control = &msgdata;
    hdr.msg_controllen = sizeof(msgdata);
  
    struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
    cmsg->cmsg_len   = hdr.msg_controllen;
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type  = SCM_RIGHTS;
  
    *(int*)CMSG_DATA(cmsg) = fd;
  
    int n = sendmsg(sock, &hdr, 0);
  
    if(n == -1)
      printf("sendmsg() failed: %s (socket fd = %d)\n", strerror(errno), sock);
  
    return n;
  }
  </code></pre>
  
  <p>Again, this works, as long as I don't call select() first to check whether the socket is ready for writing.</p>