Receiving file descriptors array by Linux socket

Viewed 91

I am trying to send and receive an array of file descriptors via linux socket.

I used cmsg(3) to create the following send function:

static bool
send_fds(int socket, int fds[])  // send array of fds by socket
{
  struct msghdr msg = {0};
  struct cmsghdr *cmsg;
  char iobuf[1];
  struct iovec io = {
      .iov_base = iobuf,
      .iov_len = sizeof(iobuf)
  };
  union {
    char buf[CMSG_SPACE(NUM_OF_FDS)];
    struct cmsghdr align;
  } u;

  msg.msg_iov = &io;
  msg.msg_iovlen = 1;
  msg.msg_control = u.buf;
  msg.msg_controllen = CMSG_SPACE(sizeof(int) * NUM_OF_FDS);

  cmsg = CMSG_FIRSTHDR(&msg);
  cmsg->cmsg_level = SOL_SOCKET;
  cmsg->cmsg_type = SCM_RIGHTS;
  cmsg->cmsg_len = CMSG_LEN(NUM_OF_FDS);

  memcpy(CMSG_DATA(cmsg), &fds, NUM_OF_FDS * sizeof(int));

  if (sendmsg (socket, &msg, 0) < 0)
  {
    debug_fn_rl(DS_STRMCLD,1,LOGT_ERROR,21442,1)("Failed to send FDs. errno: %d\n", errno);
    return false;
  }
  debug_fn(DS_STRMCLD, 3, LOGT_DEBUG, 21443)("sent fds\n");
  return true;
}

How the receive function should look like when an array is received instead of individual fd? how can I extract each fd out of the array?

0 Answers
Related