Reputation: 6031
How can I transfer the ownership of a socket between processes under Linux? Windows has a Socket.DuplicateAndClose
function, but is there a way to do this on Linux?
If it makes a difference, I would like to transfer the ownership from a parent process to a child process, and the child process won't be started yet at the time I obtain the socket, so I'm open to interesting solutions involving fork
and the exec
family of functions.
Upvotes: 3
Views: 554
Reputation: 70492
Given that you wish to spawn the child after the socket is created, there is no transfer. Child processes inherit the parent descriptors. So, the parent merely has to close the socket to pass ownership to the child.
However, to actually pass a newly created socket to an existing process,
you need to use the ancillary data interface to package your socket, and sendmsg
and recvmsg
to do the data transfer. The cmsg
manual page includes an example for how to create a message to do the transfer.
Upvotes: 2
Reputation: 7996
The child process will inherit the file descriptor. So you have nothing to do except closing the socket in the parent after you forked the child.
If you exec
another executable in the child, you may want to inform it of the file descriptor value by using a specific argument.
Upvotes: 3