问题
I have a master process and several workers, communicating using 0mq 'ipc://' sockets (UNIX domain sockets). I want to pass a file descriptor from the master to a worker, along with a message. I know that 'raw' UNIX domain sockets can be used to pass a file descriptor from one process to another, but can I do it with my zeromq sockets?
I don't care about portability, and frankly I don't care if its a slightly dirty solution. Is there any way?
Thanks in advance.
回答1:
Hackiest method would be to add a socket option to bind a file descriptor to the socket, then replace the send()
& recv()
with sendmsg()
and recvmsg()
per the required CMSG
structure to pass the descriptor.
As a global option every message would be tagged with the descriptor thus you should add suitable meta-data within the payload to indicate that the receiver should take the accompanying descriptor.
e.g. send-side
zmq_setsockopt (s, ZMQ_ANCILLIARYFD, &fd, sizeof (fd));
e.g. recv side
int incoming_fd;
size_t fd_len = sizeof (incoming_fd);
zmq_getsockopt (s, ZMQ_ANCILLIARYFD, &incoming_fd, &fd_len);
回答2:
I'm pretty certain the answer is No. A file descriptor is an integer that means something within the context of the process that called open(). In the context of another process it is meaningless. Passing that integer to another process by any method does not mean that that destination process can use it in a call to read().
File descriptors, pointers of type FILE*, anything like that are referencing objects that are almost always considered opaque. The opaqueness of that means that you can't copy it and expect it to work, which is effectively what you're trying to do by sending it through a pipe, socket, 0mq, etc.
Within a process the reference can be copied (and used by another thread for example).
The destination process can of course open the file for itself; all it needs is the filename.
来源:https://stackoverflow.com/questions/15668462/can-i-pass-a-file-descriptor-over-a-0mq-zeromq-ipc-socket