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.
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.
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().
Is there anything I can do to make this work, or does anyone know of alternative solutions?
Platform is Ubuntu 10.4.
This is the code that initializes the structures:
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)
", strerror(errno), sock);
return n;
}
Again, this works, as long as I don't call select() first to check whether the socket is ready for writing.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…